winform下ComboBox的绑定问题

来源:互联网 发布:dwg转换成pdf for mac 编辑:程序博客网 时间:2024/05/11 20:07

最近在做一个winform项目,使用到了ComboBox控件,一直被该控件的绑定烦恼着。因为该控件不能直接绑定text跟value值。

仔细研究了ComboBox.Items的add方法后,终于找到了突破口。

Add方法如下:int Add(object item)

突破口就是函数的参数类型是object类型。

可以定义一个类,包含两个属性,text,value。

然后将该类作为参数传到Add方法中。这样,就实现了text跟value值的同时绑定。

实现如下:

/// <summary>
    /// 绑定ComboBox的项,包含text,value
    /// </summary>
    public class BindItem
    {
        private string _text = null;
        private object _value = null;
        public string Text { get { return this._text; } set { this._text = value; } }
        public object Value { get { return this._value; } set { this._value = value; } }       

    }

在绑定ComboBox时,使用如下方式:

foreach (Entity en in enList)
{
BindItem bitem = new BindItem();
bitem.Text = en.name ;
bitem.Value = en.id ;
this.ComboBox.Items.Add(bitem);
}

到此,绑定完成。