ComboBox

时间:2016-02-11 09:59:57

标签: c# winforms data-binding combobox

我正在尝试使用自定义ComboBoxItem类的多个实例填充ComboBox。 ComboBoxItem类如下所示:

 class ComboBoxItem
 {
     public string Text { get; set; }
     public object Value { get; set; }

     public override string ToString()
     {
         return Text;
     }
 }

我可以填写CombBox并正确读取它的值。我唯一的问题是当现有项目进入时,值应绑定到我的ComboBox。但我不知道如何告诉Binding它应该使用ComboBoxItem.Value作为值字段。

//what to put in place of "SelectedItem"??
comboBox.DataBindings.Add(new Binding("SelectedItem", row, "F_KundenId", true, DataSourceUpdateMode.OnPropertyChanged));

2 个答案:

答案 0 :(得分:2)

这就是我在我的应用程序中绑定所有Windows ComboBox的方法:

首先使用它来加载dataSource,在本例中为List:

    public static void LoadComboBox(ComboBox comboBox, object dataSource, string valueMember, string displayMember)
    {
        comboBox.DataSource = dataSource;

        comboBox.ValueMember = valueMember;
        comboBox.DisplayMember = displayMember;
    }

然后使用它将选定的值绑定到“row”列“F_KundenId”:

    public static void BindComboBox(ComboBox comboBox, object boundDataSource, string boundDataMember)
    {
        comboBox.DataBindings.Clear();
        comboBox.DataBindings.Add("SelectedValue", boundDataSource, boundDataMember);
    }

这是一个帮助方法,可以在一次调用中完成两个任务:

public static void LoadAndBindComboBox(ComboBox comboBox, object dataSource, string valueMember, string displayMember,
    object boundDataSource, string boundDataMember)
{
    LoadComboBox(comboBox, dataSource, valueMember, displayMember);
    BindComboBox(comboBox, boundDataSource, boundDataMember);
}

此代码可以与您想要的任何数据源一起使用,并且可以绑定到DataTable,DataRow或对象的任何列。

示例:

LoadAndBindComboBox(comboBox, myItems, "Value", "Text", row, "F_KundenId");

答案 1 :(得分:0)

好的,除了Mangist的回答,我已经找到了自己的解决方案。不需要任何自定义类。只需使用DisplayMember即可。唯一的事情是你必须要小心,在运行时你设置ValueMemberDataSource。如果重置ComboBox的{​​{1}}(将其设置为null并重新绑定),则还需要设置两个Member属性。然后,只需使用Dictionary<Key, Value>对象将ComboBox绑定到BindingSource

private void InitCombos()
{
    Dictionary<string, int> items = GetItems();    
    combo.DisplayMember = "Key";
    combo.ValueMember = "Value";
    combo.DataSource = new BindingSource(items, null);
}

//This was where my problem was. I didn't set the two Member properties of my ComboBox, 
//thus preventing correct rebinding of DataSource
public void combo2_SelectedIndexChanged(object sender, EventArgs e)
{
    combo.DataSource = null;
    Dictionary<string, int> newItems = GetItems();    
    combo.DisplayMember = "Key";
    combo.ValueMember = "Value";
    combo.DataSource = new BindingSource(items, null);
}