ComboBox手工添加数据示例

ComboBox.Items.Add参数是object类型的对象,如果用数据绑定可以很容易地实现Text和Value的分别初始化(见《ComboBox绑定数据源示例》一文),但如果要手工添加数据项,就有点困难了,总结了网上方法,有以下两种:

1.使用KeyValuePair

//引用命名空间System.Collections.Generic
comboBox1.Items.Add(new KeyValuePair<string, string>("aaa", "1"));
comboBox1.Items.Add(new KeyValuePair<string, string>("bbb", "2"));
comboBox1.Items.Add(new KeyValuePair<string, string>("ccc", "3"));

comboBox1.DisplayMember = "key";
comboBox1.ValueMember = "value";

//获取值
MessageBox.Show(((KeyValuePair<string, string>)comboBox1.SelectedItem).Key + "," + ((KeyValuePair<string, string>)comboBox1.SelectedItem).Value);

2.自定义类MyListItem

MyListItem类:
public class MyListItem
{
    private string _text;
    private string _value;

    public MyListItem(string text, string value)
    {
        _text = text;
        _value = value;
    }

    public string Text
    {
        get { return _text; }
    }

    public string Value
    {
        get { return _value; }
    }

    //必须
    public override string ToString()
    {
        return _text;
    }
}

添加数据项并读取示例:

comboBox1.Items.Add(new MyListItem("aaa", "1"));
comboBox1.Items.Add(new MyListItem("bbb", "2"));
comboBox1.Items.Add(new MyListItem("ccc", "3"));

//获取值
MessageBox.Show(((MyListItem)comboBox1.SelectedItem).Text + "," + ((MyListItem)comboBox1.SelectedItem).Value);


评论: 0 | 引用: 0 | 查看次数: 5370
发表评论
登录后再发表评论!