代码改变世界

ComboBoxEdit:不能直接绑定数据源,只能手工添加。

2022-04-03 12:03  idea555  阅读(244)  评论(0)    收藏  举报

使用 ComboBoxEdit 控件添加key/value项。

因为 ComboBoxEdit 没有 DataSource 属性,所以不能直接绑定数据源,只能一项一项的添加。

public class ListItem : Object
    {
        public string Text { get; set; }

        public string Value { get; set; }

        public ListItem(string text,string value)
        {
            this.Text = text;
            this.Value = value;
        }

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

public void BindSource()
        {
            string text = string.Empty;
            string value = string.Empty;

            ListItem item = null;

            for (int i = 0; i < 4; i++)
            {
                if (i==0)
                {
                    text = "请选择";
                }
                else
                {
                    text = "选项" + i.ToString();
                }
                value = i.ToString();

                item = new ListItem(text, value);
                this.comboBoxEdit1.Properties.Items.Add(item);
            }
        }

获取选中项的值时,注意判断是否选择。

string text = string.Empty;
string value = string.Empty;

if (comboBoxEdit1.SelectedIndex < 0)    //小于0,表示未选择,如果是输入的也小于0
{
     text = comboBoxEdit1.Text.Trim();     //只能获取输入的文本
}
else
{
     text= (comboBoxEdit1.SelectedItem as ListItem).Text;        //获取选中项文本
     value = (comboBoxEdit1.SelectedItem as ListItem).Value;        //获取选中项的值