木子屋 Dnawo's BLOG

ComboBox手工添加数据示例

👤 dnawo 📅 2009-10-12 👁 6034 👍 0 💬 0 🔄 本站原创
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)

暂无评论。

计算题
评论需审核通过后显示
← 上一篇 VB6.0模块和类模块区别 下一篇 → MDI子窗体Load事件中设置DataGridView行高、背景…