我目前很难从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();
答案 0 :(得分:3)
当您将ComboBox链接到数据源并希望返回除显示的值之外的值时,将使用SelectedValue属性。
例如,一种替代方法可能是创建一个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);
}
答案 1 :(得分:0)
投射组合框的SelectedItem
属性
var selectedItem = comboBox8.SelectedItem as ComboboxItem;
if (selectedItem != null)
{
// Do something with the selectedItem.Value or selectedItem.Text
}
答案 2 :(得分:0)
您也可以尝试这种方法。
绑定组合框后,您必须设置:
comboBox8.ValueMember = "DBFieldName1";
comboBox8.DisplayMember = "DBFieldName2";
if(comboBox8.SelectedItem != null)
{
string text=comboBox8.SelectedItem.ToString();
string value=comboBox8.SelectedValue.ToString();
}
注意: - 还要确保读者不会返回任何空值或重复值。
希望这会有所帮助:)