简体   繁体   中英

passing parameters using selected value from combo box in c#

I have a combobox1 on my form which is bound by a data source, it displays values from my data table.

I then have combobox2 which needs to populate but the store procedure that fires requires a parameter.

How can i pass the selectedValue from combobox1 into the datasource so that combobox2 will show up with its values?

This is my code so far:

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    string databaseName = string.Empty;
    if (comboBox1.SelectedValue != null) databaseName = comboBox1.SelectedValue.ToString();
    comboBox2.DataSource(FindColumn.GetData(databaseName));
}

This is example how to get ComboBox binded to DataTable data source and how to get the value out of selected item (so that later you can use that value to fill another combobox)

 // On constructor - Quickly create some table and fill with some data
 DataTable dt = new DataTable();
 dt.Columns.Add("a");
 dt.Columns.Add("b");
 dt.Columns.Add("c");
 dt.Rows.Add("1", "2", "aaa");
 dt.Rows.Add("3", "4", "bbb");
 // setup combo box data binding
 comboBox1.DataSource = dt;
 comboBox1.DisplayMember = "b";
 comboBox1.ValueMember = "a";

Notice that we don't reference column "c"

void button1_click()
{
    MessageBox.Show(((DataRowView )comboBox1.SelectedItem)[2].ToString ());
}

This will result in "aaa" or "bbb" shown. Now, you can use that value to call your stored proc.

Basically, when you bind DataTable , each combo item is a DataRowView . All your table data is available for the row you've selected.

Notice

comboBox1.DisplayMember = "b";
comboBox1.ValueMember = "a";

Usually this is enough. You would use some id as ValueMember and use that id to do your CRUD operations. But again, example above shows that you can have more different values available via SelectedItem property.

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