mitul
mitul

Reputation: 11

How to show record in DataGridView based on selected ComboBox item?

I am making windows application and am stuck at one place. My problem is that i want to display record in a DataGridView by selecting a ComboBox item but I do not understand the proper way to do it. Please help me in overcome this problem.

private void grid_Load(object sender, EventArgs e)
{
con = new SqlConnection(constr);

    try
    {
        con.Open();
        //this.studTableAdapter.Fill(this.pRJTestDBDataSet.stud);
        //above line show error for connection to database

        da = new SqlDataAdapter("SELECT stud_no FROM stud", con);
        DataTable dt = new DataTable();
        da.Fill(dt);
        comboBox1.DataSource = dt;
        comboBox1.DisplayMember = "stud_no";
        comboBox1.ValueMember = "stud_no";
        comboBox1.DataSource = dt;
        comboBox1.SelectedIndex = -1;
        comboBox1_SelectedIndexChanged(sender, e);
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
    finally
    { con.Close(); }
}

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    this.studTableAdapter.Fill(pRJTestDBDataSet.stud);
    //above line show error for connection to database
}

i have tried above code but its not working there error like login fail to user

Upvotes: 1

Views: 3698

Answers (3)

Gautam Jaiswal
Gautam Jaiswal

Reputation: 1

 private void button2_Click(object sender, EventArgs e)//button 2 is a show data button
    {
        if (combo_floor.Text != "")
        {

            DataSet ds = new DataSet();
            string sql = "select floor_id,floor_no,floor_remark,floor_entrydate from Floorinfo where floor_no='"+combo_floor.Text+"'";
            ds = c.select_query(sql);
            dataGridView1.DataSource = ds.Tables["a"];
            combo_floor.Text = "";
        }

        else
        {
            showdata();
            //showdata()is made for show all data from the given table name
        }


    }

//connection is in different class so please dont mind

Upvotes: -1

zzz
zzz

Reputation: 23

    cmd = new SqlCommand("SELECT stud_no FROM stud", con);
    da = new SqlDataAdapter(cmd);

    da.Fill(dt);
    Combobox1.DataSource = dt;
    Combobox1.DisplayMember = dt.Columns("Stud_no").ToString;

Upvotes: 2

Ali
Ali

Reputation: 135

rebind the DataGrid at each SelectedItemIndex change event of Combo Box by the data you want to bind.

Upvotes: 0

Related Questions