簡體   English   中英

在從 DataTable 填充的組合框中選擇一個值

[英]Selecting a value in combobox that's populated from a DataTable

我有一個由 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";

您是否嘗試設置 SelectedValue? 您有一個 Id,並聲明 ValueMember 是 Id,然后使用它。

您可以這樣做,它可以工作,但如果您有大量物品,則不會太快:

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

您可以通過查找與指定字符串完全匹配的項目來設置SelectedIndex ComboBox.FindStringExact 方法

cbRates.SelectedIndex = cbRates.FindStringExact("Value_need_to_Select") ;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM