选择从数据表填充的组合框中的值

问题描述 投票:3回答:4

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

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

c# .net combobox compact-framework
4个回答
3
投票

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

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

2
投票

您是否尝试设置SelectedValue?您有一个ID,并声明ValueMember为ID,然后使用它。


1
投票

您可以执行此操作,但可以正常运行,但是如果有大量物品,则不会太快:

foreach (object item in comboBox1.Items)
{
    DataRowView row = item as DataRowView;
    if ((String)row["YourDisplayMemberColumn"] == "ValueYouWantToSelect")
    {
        comboBox1.SelectedItem = item;
    }
}

0
投票

您可以通过找到与指定字符串ComboBox.FindStringExact方法完全匹配的项目来设置SelectedIndex

cbRates.SelectedIndex = cbRates.FindStringExact("Value_need_to_Select") ;
© www.soinside.com 2019 - 2024. All rights reserved.