1

我目前很难从 C# 中的组合框中检索值。组合框项是从数据库中填充的。这就是我填写项目的方式:

while (reader.Read())

                {
                    ComboboxItem item = new ComboboxItem();
                    item.Text = (string)reader[0];
                    item.Value = (string)reader[1];
                    comboBox8.Items.Add(item);

                }

此命令显示文本,但不显示值:

String s = comboBox8.SelectedItem.ToString();

并且此命令引发“System.NullReferenceException”

String s = comboBox8.SelectedValue.ToString();
4

3 回答 3

3

SelectedValue 属性用于将 ComboBox 链接到数据源并希望返回与显示内容不同的值。

例如,一种替代方法可能是创建一个 DataTable,将您的数据库读数放入其中,并在那里分配组合框选定的值和文本。例如;

DataTable dataTable = new DataTable();
//column 1 name, which will be display member
dataTable.Columns.Add(new DataColumn("nameOfYourTextField"); 
//column 2 name, which will be your value member
dataTable.Columns.Add(new DataColumn("nameOfYourValueField"); 

//assign your datasource (the datatable) to the combobox
comboBox8.DataSource = dataTable; 

//and finally assign your value member (the text you want returning)
comboBox8.ValueMember = "nameOfYourValueField";
//and your display member (the text visible in the combobox)
comboBox8.DisplayMember = "nameOfYourTextField";

然后在你的读者中;

while (reader.Read())

            { 
                //create a new row which matches the signature of your datatable
                DataRow row = dataTable.NewRow();
                //assign data to the rows, given a certain column name
                row["nameOfYourValueField"] = reader[1];
                row["nameOfYourTextField"] = reader[0];
                //and add the row to the datatable
                dataTable.Rows.Add(row);

            }
于 2013-04-11T13:09:32.937 回答
0

转换组合框的SelectedItem属性

var selectedItem =  comboBox8.SelectedItem  as ComboboxItem;
if (selectedItem != null)
{
    // Do something with the selectedItem.Value or selectedItem.Text
}
于 2013-04-11T12:59:23.307 回答
0

你也可以试试这个方法。

绑定组合框后,您必须设置:

 comboBox8.ValueMember = "DBFieldName1";
 comboBox8.DisplayMember = "DBFieldName2";

 if(comboBox8.SelectedItem != null)
 {
        string text=comboBox8.SelectedItem.ToString();
        string value=comboBox8.SelectedValue.ToString();
 }

注意: -还要确保阅读器不返回任何空值或重复值。

希望这可以帮助 :)

于 2013-04-11T13:05:18.590 回答