zoukankan      html  css  js  c++  java
  • Winfrom 中 ComboBox 绑定数据后设置选定项问题

    在为 ComboBox 当定数据的时候,如果遇到界面显示需要用文本,而获取选定项的值时需要用数字,我们就很习惯使用 DataSource  来进行绑定。

    例如以下代码:

     List<TextValue> tvList = new List<TextValue>();
     for (int i = 0; i < 4; i++)
    {
        tvList.Add(new TextValue(i.ToString(), i));
    }
     ComboBox cmb = new ComboBox();
    cmb.DataSource = tvList;
    cmb.DisplayMember = "Text";
    cmb.ValueMember = "Value";
    cmb.SelectedIndex = 0;

    但是这么做,在最后一行设置下拉列表框选定项的时候会出现异常,因为这样直接绑定后,下拉列表框的 Items 属性中的数据长度是 0。但是我们又必须设置选定项,这个时候我用了一下代码:

    ComboBox cmb = new ComboBox();
    for (int i = 0; i < 4; i++)
    {
        cmb.Items.Add(new TextValue(i.ToString(), i));
    }
    cmb.DisplayMember = "Text";
    cmb.ValueMember = "Value";
    cmb.SelectedIndex = 0;
    /// <summary>
    /// ComboBox的Item
    /// </summary>
    public class TextValue
    {
        public TextValue() { }
    
        public TextValue(string inText, int inValue)
        {
            this.Text = inText;
            this.Value = inValue;
        }
    
        private string _text;
        private int _value;
        /// <summary>
        /// 文本
        /// </summary>
        public string Text
        {
            set { this._text = value; }
            get { return this._text; }
        }
        /// <summary>
        ////// </summary>
        public int Value
        {
            set { this._value = value; }
            get { return this._value; }
        }
    }

    这么做既可以让下拉列表框做到显示和背后的值的分离,也可以立刻设置选定项。

  • 相关阅读:
    php DOC类型注释的用法
    Mysql 数据库更新错误
    Smarty初体验二 获取配置信息
    Smarty 模板初体验
    去网络视频广告方法——虽过时,但效果依然很好(亲测)
    织梦模板修改方法大全
    dede织梦:文章内容页调用
    织梦系统学习:文章页当前位置的写法(自认对SEO有用)
    ZOJ 3229 Shoot the Bullet
    URAL 1277 Cops and Thieves
  • 原文地址:https://www.cnblogs.com/rogation/p/3435243.html
Copyright © 2011-2022 走看看