簡體   English   中英

winforms動態組合框默認值

[英]winforms dynamic combobox default value

好的,所以我有兩個組合框,一個組合框裝有修飾符(Ctrl,Alt,Shift,Windows鍵),另一個組合有鍵(AZ,F1-F12)。 我想將那些組合框的默認值更改為保存在“ Properties.Settings.Default。*”中的那些組合框,只是某種程度上它無法正常工作。

這是填充組合框的代碼:

private void Settings_Load(object sender, EventArgs e)
{
    KeyModifiers[] modifierArray = new KeyModifiers[] { KeyModifiers.Alt, KeyModifiers.Control, 
                                                        KeyModifiers.Shift, KeyModifiers.Windows };

    var dataSourceModifiers = new List<KeyModifiers>();

    foreach(KeyModifiers modifier in modifierArray )
    {
        dataSourceModifiers.Add(modifier);
    }

    this.comboboxClickerModifier.DataSource = dataSourceModifiers;

    Keys[] keysArray = new Keys[] { Keys.A, Keys.B, Keys.C, Keys.D, Keys.E, Keys.F, Keys.G, Keys.H, Keys.I, Keys.J, Keys.K,
                                    Keys.L, Keys.M, Keys.N, Keys.O, Keys.P, Keys.Q, Keys.R, Keys.S, Keys.T, Keys.U, Keys.V, 
                                    Keys.W, Keys.X, Keys.Y, Keys.Z, Keys.F1, Keys.F2, Keys.F1, Keys.F2, Keys.F3, Keys.F4, Keys.F5,
                                    Keys.F6, Keys.F7, Keys.F8, Keys.F9, Keys.F10, Keys.F11, Keys.F12};

    var dataSourceKeys = new List<Keys>();

    foreach (Keys key in keysArray)
    {
        dataSourceKeys.Add(key);
    }

    this.comboboxClickerKey.DataSource = dataSourceKeys;

    // Down here are the ways I tried to set the default value
    comboboxClickerKey.Text = Properties.Settings.Default.Key.ToString();
    comboboxClickerKey.SelectedIndex = comboboxClickerKey.Items.IndexOf(Properties.Settings.Default.Key);
    comboboxClickerKey.SelectedItem = Properties.Settings.Default.Key;
    comboboxClickerModifier.SelectedItem = Properties.Settings.Default.Modifier;
}

在代碼底部,您可以看到我嘗試設置默認值的方法,但是所有方法都沒有這樣做。

設置: http://puu.sh/if5aJ.png

啟動窗口: http://puu.sh/if5jW.png

我建議將對應的ComboBox控件的選定索引存儲在Properties.Settings.Default.IndexModifierProperties.Settings.Default.IndexKey (類型int )中,例如:

Properties.Settings.Default.IndexKey=comboboxClickerKey.SelectedIndex;
Properties.Settings.Default.Save();

並分別使用該索引值進行操作,以迫使ComboBox控件返回以顯示適當的項目,例如:

comboboxClickerKey.SelectedIndex=Properties.Settings.Default.IndexKey

該代碼將更加簡潔,不包括大量的類型轉換。 另外,這里是描述各種ComboBox數據綁定技術的文章的鏈接(與ASP.NET相關的示例也可以輕松地應用於WinForms應用): http : //www.codeproject.com/Tips/214418/Binding-DropDownList到各種數據結構

注意 :關於您的代碼段,最接近有效的解決方案是以下行:

comboboxClickerKey.Text = Properties.Settings.Default.Key.ToString();

接下來的3行看起來不正確,很可能會導致異常。 如果不顯式綁定DataTextFieldDataValueField ,則可能會起作用。 否則可能會失敗。

希望這會有所幫助。

暫無
暫無

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

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