2013-05-14 39 views
1

comboBox的DataSource是一個DataTable。 DataTable有一個名爲ID的鍵列,ID的值可以是1,2,3,4,5。將組合框的SelectedIndex設置爲基礎數據源中的鍵值所找到的索引?

我想設置組合框的SelectedIndex對應於我想要的ID。這裏是我的嘗試,它的工作原理確定,但我不知道這是最好的:

DataTable source = (DataTable) myComboBox.DataSource; 
DataRow[] rows = source.Select(string.Format("ID='{0}'", 3));//the ID I want is 3 
myComboBox.SelectedIndex = rows.Length == 0 ? -1 : source.Rows.IndexOf(rows[0]); 

你有其他更好的解決辦法?

非常感謝!

+0

你目前的解決方案看起來很好,你爲什麼要改變它? – Habib 2013-05-14 04:38:01

+0

@Habib不,我正在使用它,如果有更好的解決方案,我只是有點好奇。謝謝。 – 2013-05-14 04:39:03

回答

1

我已經嘗試過自己,但我不確定它們是否比我在原始問題中發佈的更好。在這裏,他們是:

  1. 使用的BindingSourceFind()方法:

    //Only 1 line of code, seems to much cleaner :) 
    myComboBox.SelectedIndex = new BindingSource(myComboBox.DataSource,"").Find("ID",3); 
    //In fact, I thought of this before but I had tried the solution in my OP first. 
    
  2. 使用一個小竅門與FindStringExact()方法ComboBox

    string currentDisplayMember = myComboBox.DisplayMember; 
    myComboBox.DisplayMember = "ID"; 
    myComboBox.SelectedIndex = myComboBox.FindStringExact("3"); 
    myComboBox.DisplayMember = currentDisplayMember; 
    

#2應如果你有與有關的東西,請小心使用當SelectedIndexChanged被解僱時處理。

我希望這可以幫助他人。如果它們比我在原始問題中使用的方法更好,請在下面留下您的評論。謝謝!

相關問題