首先自定义自己的数据类型:
public class ComboBoxItem<T, K>
{
private T _value;
public T Value
{
get { return _value; }
set { _value = value; }
}
private K _caption;
public K Caption
{
get { return _caption; }
set { _caption = value; }
}
public ComboBoxItem(T value, K caption)
{
this._caption = caption;
this._value = value;
}
public override string ToString()
{
if (_caption != null)
return _caption.ToString();
else
return "";
}
}
现在的任务就是将ComboBoxItem类型绑定给ComboBox
ComboBox.ValueMember = "Value";
ComboBox.DisplayMember = "Caption";
List<ComboBoxItem<int, string>> items = new List<ComboBoxItem<int, string>>();
items.Add(new ComboBoxItem<int, string>("Value1", "Txt1"));
items.Add(new ComboBoxItem<int, string>("Value2", "Txt2"));
ComboBox.DataSource = items;
使用这种绑定方法,可以得到
ComboBox.SelectedValue,
我看了园子里面有些人的自定义绑定方法,但是基本上都不能获取 ComboBox.SelectedValue的值
他们都是通过 ComboBox.SelectedItem转换为绑定类型,然后再获取该类型的Value字段