我有一個組合框由DataTable填充,如下所示。我希望能夠設置顯示哪個項目。要設置的值是一個字符串,可以在「Id」列中找到。從DataTable填充的組合框中選擇一個值
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;
我碰到下面的錯誤;但是,如果爲了測試目的將相關代碼放入它自己的窗體中,我可以無誤地設置selectedIndex。
我認爲這些問題是關聯的。
我試圖this.cbRates.SelectedValue = answerSplit [1];那也沒用。 – Mark 2011-03-23 10:55:56