2011-03-23 94 views
3

我有一個組合框由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。

我認爲這些問題是關聯的。

回答

2

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

+0

我試圖this.cbRates.SelectedValue = answerSplit [1];那也沒用。 – Mark 2011-03-23 10:55:56

3

您是否知道可以直接將數據表用作數據源?

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

我是,「列表」是我的數據表 - this.cbRates.DataSource =列表; this.cbRates.DisplayMember =「Display」; this.cbRates.ValueMember =「Id」; – Mark 2011-03-23 11:09:30

+0

然後,使用SelectedValue屬性:cbo.SelectedValue =「234」(假設「234」是表中的ID之一) – Morten 2011-03-23 11:38:52

+0

我已經試過了,它似乎沒有做任何事情。嘗試使用包含= Id的字符串的變量,然後將其硬編碼爲100%確定它使用的是正確的值。 – Mark 2011-03-23 12:00:34

1

你可以做到這一點,它的工作,但不能太快,如果你有一大堆的項目:

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