我有一个由DataTable填充的组合框,如下所示。我希望能够设置显示的项目。它要设置的值是一个字符串,可以在“Id”列中找到。
public DataTable list = new DataTable();
public ComboBox cbRates = new ComboBox();
//prepare rates combo data source
this.list.Columns.Add(new DataColumn("Display", typeof(string)));
this.list.Columns.Add(new DataColumn("Id", typeof(string)));
//populate the rates combo
int counter = 0;
foreach (string item in dropdownItems)
{
this.list.Rows.Add(list.NewRow());
if (counter == 0)
{
this.list.Rows[counter][0] = "Select Rate..";
this.list.Rows[counter][1] = "";
}
else
{
string[] itemSplit = item.Split('`');
if (itemSplit.Length == 2)
{
this.list.Rows[counter]["Display"] = itemSplit[0];
this.list.Rows[counter]["Id"] = itemSplit[1];
}
else
{
this.list.Rows[counter]["Display"] = item;
this.list.Rows[counter]["Id"] = item;
}
}
counter++;
}
this.cbRates.DataSource = list;
this.cbRates.DisplayMember = "Display";
this.cbRates.ValueMember = "Id";
//now.. how to set the selected value?
int rowCount = 0;
foreach (DataRow cbrow in this.list.Rows)
{
if (DB.GetString(cbrow["Id"]) == answerSplit[1])
{
//attempting to set the SelectedIndex throws an exception
//on another combobox populated NOT from a DataTable - this does work fine.
this.cbRates.SelectedIndex = rowCount;
}
rowCount++;
}
//this doesn't seem to do anything.
foreach (DataRow dr in this.list.Rows)
{
if ((string)dr["Id"] == answerSplit[1]) this.cbRates.SelectedItem = dr;
}
//nor this
foreach(DataRow dr in this.cbRates.Items)
{
try
{
if ((string)dr["Id"] == answerSplit[1]) this.cbRates.SelectedItem = dr;
}
catch
{
MessageBox.Show("Ooops");
}
}
如果没有FindExactString,FindString,FindByValue在紧凑的框架中不存在,我将无法尝试。
如果尝试使用
this.cbRates.SelectedIndex = 2;
我收到以下错误;
System.Exception: Exception
at Microsoft.AGL.Common.MISC.HandleAr(PAL_ERROR ar)
at System.Windows.Forms.ComboBox.set_SelectedIndex(Int32 value)
但是,如果我将相关代码放入其自己的表单中以进行测试,我可以设置selectedIndex而不会出错。
我认为这些问题是相互关联的。
答案 0 :(得分:3)
您是否知道可以直接将数据表用作数据源?
cbo.DataSource = table;
cbo.DisplayMember = "Display";
cbo.ValueMember = "Id";
答案 1 :(得分:2)
您是否尝试设置SelectedValue?您有一个Id,并且您声明ValueMember是Id,然后使用它。
答案 2 :(得分:1)
你可以做到这一点,如果你有大量的物品,它可以工作但不会太快:
foreach (object item in comboBox1.Items)
{
DataRowView row = item as DataRowView;
if ((String)row["YourDisplayMemberColumn"] == "ValueYouWantToSelect")
{
comboBox1.SelectedItem = item;
}
}
答案 3 :(得分:0)
您可以通过找到与指定字符串ComboBox.FindStringExact方法完全匹配的项目来设置SelectedIndex
cbRates.SelectedIndex = cbRates.FindStringExact("Value_need_to_Select") ;