我有一个由数据表填充的组合框,如下所示。我希望能够设置显示哪个项目。它将被设置为的值是将在“ 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而不会出现错误。

我认为这些问题是相关的。

最佳答案

您是否知道可以将数据表直接用作数据源?

        cbo.DataSource = table;
        cbo.DisplayMember = "Display";
        cbo.ValueMember = "Id";

08-26 19:06