C# Combobox 设置 value

时间:2021-10-06 01:04:19

因为ComboxItem是Object对象,而控件自身没有Value属性.所以,需要自定义一个类,用其对象来存储Text,Value.

public class ComboxItem
    {
        private string text;
        private string values;

public string Text
        {
            get { return this.text; }
            set { this.text = value; }
        }

public string Values
        {
            get { return this.values; }
            set { this.values = value; }
        }

public ComboxItem(string _Text, string _Values)
        {
            Text = _Text;
            Values = _Values;
        }


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


赋值示例一:

    cbDictData.Items.Add(new ComboxItem("用户类型", "D1"));
            cbDictData.Items.Add(new ComboxItem("地区字典", "D2"));
            cbDictData.Items.Add(new ComboxItem("区域字典", "D3")); 
  
赋值示例二:

ComboxItem[] values = {
                new ComboxItem("用户类型", "D1"),
                new ComboxItem("地区字典", "D2"),
                new ComboxItem("区域字典", "D3")
            };
            cbDictData.Items.AddRange(values);

取值示例:

string strDict = ((ComboxItem)cbDictData.SelectedItem).Values;