2012-09-26 67 views
3

我有一個綁定到一個字典這樣的組合框:設置所選項目勢必字典

Dictionary<int, string> comboboxValues = new Dictionary<int, string>(); 
comboboxValues.Add(30000, "30 seconds"); 
comboboxValues.Add(45000, "45 seconds"); 
comboboxValues.Add(60000, "1 minute"); 
comboBox1.DataSource = new BindingSource(comboboxValues , null); 
comboBox1.DisplayMember = "Value"; 
comboBox1.ValueMember = "Key"; 

我收到來自的SelectedItem這樣的關鍵:

int selection = ((KeyValuePair<int, string>)comboBox1.SelectedItem).Key; 

因此,如果我的用戶選擇「45秒」選項,我會返回45000並將該值保存到XML文件。當我的應用程序加載時,我需要讀取該值,然後自動設置組合框以匹配。當我只有45000的密鑰時,可以這樣做嗎?或者我需要將值(「45秒」)保存到文件而不是密鑰?

回答

6

是的,你可以只使用45000

comboBox1.SelectedItem = comboboxValues[45000]; 

如果你知道索引,那麼你可以使用

comboBox1.SelectedIndex = i; 

我是從零開始,-1表示沒有選擇。

或者設置的SelectedItem

comboBox1.SelectedItem = new KeyValuePair<int, string>(45000, "45 seconds"); 

private void Form1_Load(object sender, EventArgs e) 
{ 
    Dictionary<int, string> comboboxValues = new Dictionary<int, string>(); 
    comboboxValues.Add(30000, "30 seconds"); 
    comboboxValues.Add(45000, "45 seconds"); 
    comboboxValues.Add(60000, "1 minute"); 
    comboBox1.DataSource = new BindingSource(comboboxValues, null); 
    comboBox1.DisplayMember = "Value"; 
    comboBox1.ValueMember = "Key"; 
    comboBox1.SelectedItem = comboboxValues[45000]; 
} 
+0

我一直在努力的第一個建議(comboBox1.SelectedItem =預先選擇comboboxValues [45000];)但它不適合我。沒有錯誤發生,它只是沒有產生預期的效果。我目前正在使用switch語句作爲鍵,然後根據第三個建議設置SelectedItem。這適用於我,但我覺得硬編碼開關值不是一個非常靈活的解決方案。任何想法,爲什麼你的第一個建議似乎不工作? – user685869

+0

這是來自我實際測試過的代碼。我希望你先把這個kvp放在字典中?並綁定它。 – Paparazzi

+0

很奇怪。我剛剛創建了一個新的WinForms應用程序,將上面的確切代碼粘貼到Form1_Load事件處理程序中,並在調試程序中逐步完成。當我的表單出現時,組合框顯示「30秒」(正如我期待的comboBox1.SelectedItem = comboboxValues [30000];語句)。然而,我然後回去編輯該行爲comboBox1.SelectedItem = comboboxValues [45000],當表單出現時,組合框仍然顯示「30秒」而不是「45秒」。如果它適合你,我一定會在這裏丟失一些明顯的東西,但我肯定不知道它是什麼。 :-( – user685869

1

只需使用

comboBox1.SelectedValue=45000 

,你的組合框將通過使用密鑰