0

我的问题是,当我在我的文本框中写一些东西时,我的组合框会清除它的选择。这只发生在一个特定的组合框上,该组合框使用下面的代码进行数据绑定。

private void FillEmployemenetType()
{
    var items = new BindingList<KeyValuePair<string, string>>();

    items.Add(new KeyValuePair<string, string>("C", "Contract"));
    items.Add(new KeyValuePair<string, string>("P", "Permanent"));
    items.Add(new KeyValuePair<string, string>("V", "Vacation"));

    contractTypeComboBox.DataSource = items;
    contractTypeComboBox.ValueMember = "Key";
    contractTypeComboBox.DisplayMember = "Value";
    contractTypeComboBox.SelectedIndex = 0;
} 

我没有触发任何文本更改事件或为此编写任何代码。我为此窗口窗体使用绑定源,以防万一这可能是问题。

4

1 回答 1

0

您可以在设置数据源后尝试设置SelectedItem,以便重新选择上一项。

private void FillEmployemenetType()
{
    KeyValuePair<string,string>? previous = null;
    if (contractTypeComboBox.DataSource != null) {
        previous = (KeyValuePair<string,string>)contractTypeComboBox.SelectedItem;
    }

    var items = new BindingList<KeyValuePair<string, string>>();

    items.Add(new KeyValuePair<string, string>("C", "Contract"));
    items.Add(new KeyValuePair<string, string>("P", "Permanent"));
    items.Add(new KeyValuePair<string, string>("V", "Vacation"));

    contractTypeComboBox.DataSource = items;
    contractTypeComboBox.ValueMember = "Key";
    contractTypeComboBox.DisplayMember = "Value";
    //contractTypeComboBox.SelectedIndex = 0;
    if (previous.HasValue) {
        try {
            contractTypeComboBox.SelectedItem = previous;
        }
        catch { }
    }
} 
于 2013-03-04T11:09:21.410 回答