c# - 在从 DataTable 填充的组合框中选择一个值

标签 c# .net combobox compact-framework

我有一个由 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。

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

最佳答案

你知道你可以直接使用数据表作为数据源吗?

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

关于c# - 在从 DataTable 填充的组合框中选择一个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5403943/

相关文章:

c# sockets 缺少数据

c# - 将大型 SQL 查询移至 Excel

c# - 通过 NAT/防火墙进行 P2P 数据传输的开源库或类

c# - .NET Framework 4.5 Full Install 为什么只有 50MB(因为他们不再有 Client Profile)?

c# - 简单的 WPF 组合框过滤器

WPF/XAML - 允许 ComboBox 具有不在 ItemsSource 中的 SelectedValue

c# - 无法使用 ClickOnce 安装 stdole.dll

c# - 这可以单独使用格式化字符串来完成吗?

c# - 注册不同的实现

c# - 动态生成的组合框值