简体   繁体   中英

getting data from combobox to a datagridview

I am using windows forms application. I have two combo boxes , comboA and comboB.I have a datagrid view with two columns. Now I have to populate the datagrid view, with selected item from comboA into first column of datagridview and selected item of comboB into the second column. Please suggest me.

To be clear, When I select an item from comboA, it should be displayed in first column of datagridview. And similary when i select an item from comboB , it should be displayed in the second column of the datagridview.

Assuming you want to populate the first row in your datagridview:

private void comboBox1_SelectionChangeCommitted(object sender, EventArgs e)
{
    this.dataGridView1.Rows[0].Cells[0].Value = comboBox1.Text;
}

private void comboBox2_SelectionChangeCommitted(object sender, EventArgs e)
{
    this.dataGridView1.Rows[0].Cells[1].Value = comboBox2.Text;
}

I did it. Here is the code.

DataTable dt2 = new DataTable(); 
DataRow dr2 = null; 
dt2.Columns.Add("key"); 
dt2.Columns.Add("value");
 dr2 = dt2.NewRow(); 
dr2["key"] = comboA.SelectedItem.ToString(); 
dr2["value"] = comboB.SelectedItem.ToString(); 
dt2.Rows.Add(dr2); 
this.dataGridView1.DataSource = dt2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM