1

我有一个带有组合框的表格。我正在读取一个文件,并且文件中包含我需要预先填充此组合框的信息。示例:组合框的填充如下:

        DataTable dataTable = new DataTable("Letters");
        dataTable.Columns.Add("One");
        dataTable.Columns.Add("Two");
        dataTable.Rows.Add("AB", "Alpha Bravo");
        dataTable.Rows.Add("BC", "Bravo Charlie");
        dataTable.Rows.Add("CD", "Charlie Delta");
        dataTable.Rows.Add("DE", "Delta Echo");
        cbLetters.DataSource = dataTable;
        cbLetters.DisplayMember = "Two";
        cbLetters.ValueMember = "One";
        cbLetters.SelectedItem = 1;
        cbLetters.Refresh();

当我这样搜索时: cbLetters.SelectedValue = FieldFromFile.ToString(); 我不检索任何记录。FieldFromFile 充满了“CD”。我也试过 cbLetters.SelectedValue = FieldFromFile。

当我这样搜索时: cbLetters.SelectedValue = "CD"; 我按预期找回了查理三角洲。

这太痛苦了。不用说我是 C# 的新手。任何帮助将不胜感激。

非常感谢!

4

1 回答 1

0

问题是没有得到值,问题是 set datasource ,注意 ComboBox 不包含元素。例如:

DataTable dataTable = new DataTable("Letters");
dataTable.Columns.Add("One");
dataTable.Columns.Add("Two");
dataTable.Rows.Add("AB", "Alpha Bravo");
dataTable.Rows.Add("BC", "Bravo Charlie");
dataTable.Rows.Add("CD", "Charlie Delta");
dataTable.Rows.Add("DE", "Delta Echo");
var cbLetters = new ComboBox();
cbLetters.DataSource = dataTable.DataSet;
cbLetters.DisplayMember = "Two";
cbLetters.ValueMember = "One";
cbLetters.Refresh();
var foo = cbLetters.Items.Count;
Console.Write(foo); //retun 0

编辑:问题是您的代码没有任何 DataBind "cbLetters.DataBind();",

DataTable dataTable = new DataTable("Letters");
dataTable.Columns.Add("One");
dataTable.Columns.Add("Two");
dataTable.Rows.Add("AB", "Alpha Bravo");
dataTable.Rows.Add("BC", "Bravo Charlie");
dataTable.Rows.Add("CD", "Charlie Delta");
dataTable.Rows.Add("DE", "Delta Echo");

var cbLetters = new DropDownList();
cbLetters.DataSource = dataTable.DefaultView;
cbLetters.DataSource = new BindingSource(dataTable, null);
cbLetters.DataValueField = "one";
cbLetters.DataTextField = "two";
cbLetters.DataBind();  // Here DataBind  
cbLetters.SelectedIndex = 2;
//cbLetters.Refresh();
Console.Write("value selected -> " + cbLetters.SelectedValue); //return CD
Console.Write("text selected -> " + cbLetters.SelectedItem.Text); // return Charlie Delta
于 2013-06-03T19:21:57.007 回答