简体   繁体   English

使用C#组合框中的选定值传递参数

[英]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. 我的表单上有一个由数据源绑定的combobox1 ,它显示数据表中的值。

I then have combobox2 which needs to populate but the store procedure that fires requires a parameter. 然后,我有需要填充的combobox2 ,但是触发的存储过程需要一个参数。

How can i pass the selectedValue from combobox1 into the datasource so that combobox2 will show up with its values? 我怎样才能将combobox1的selectedValue传递到数据源,以便combobox2会显示其值?

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) 这是示例如何将ComboBox绑定到DataTable数据源以及如何从所选项目中获取值(以便以后可以使用该值填充另一个组合框)

 // 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" 请注意,我们没有引用“ c”列

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

This will result in "aaa" or "bbb" shown. 这将导致显示“ aaa”或“ bbb”。 Now, you can use that value to call your stored proc. 现在,您可以使用该值来调用存储的proc。

Basically, when you bind DataTable , each combo item is a DataRowView . 基本上,当您绑定DataTable ,每个组合项都是一个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. 您将使用一些ID作为ValueMember并使用该ID进行CRUD操作。 But again, example above shows that you can have more different values available via SelectedItem property. 但是,上面的示例再次表明,可以通过SelectedItem属性获得更多不同的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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