combox如何添加带Value和Text的item

初学winform的时候,一直以为winform中的combox只能添加简单的仅有text的item,而不象aspx中的listitem那样即有text,又有value,结果很快发现自己错了,以下是一个示例:

先声明一个类

    public class ClsItemObject
    {
        public string ClassName = "", ClassId = "";

        public ClsItemObject(string _clsName, string _clsId) 
        {
            ClassName = _clsName;
            ClassId = _clsId;
        }

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

 

利用这个类,我们可以直接在combox中添加复杂类型的item

ClsItemObject[] co = new ClsItemObject[3];
            co[0] = new ClsItemObject("精美礼品", "001");
            co[1] = new ClsItemObject("--手工礼品", "002");
            co[2] = new ClsItemObject("家用电器", "333");
            comboBox1.Items.AddRange(co);
            comboBox1.SelectedIndex = 1;

取值时,要记得用强制类型转换,转换成正确的类型

 ClsItemObject coSelected = (ClsItemObject)comboBox1.SelectedItem;
            MessageBox.Show(coSelected.ClassId);

使用一例:

  1. public class StringIntObject
  2.         {
  3.             public string Text;
  4.             public int Value;

  5.             public StringIntObject(string text, int value)
  6.             {
  7.                 Text = text;
  8.                 Value = value;
  9.             }

  10.             public override string ToString()
  11.             {
  12.                 return Text;
  13.             }
  14.         }

  15.         public void RefreshHubGroup()
  16.         {
  17.             this.comboBox3.Items.Clear();
  18.             CLocalTabStruct.SHubGroupParam[] records = null;
  19.             CAccessLayer.GetHubGroupParam(out records);
  20.             if (records == null)
  21.                 return;

  22.             StringIntObject[] so = new StringIntObject[records.Length];
  23.             for (int i = 0; i records.Length; i++)
  24.                 so[i] = new StringIntObject(records[i].GroupName, records[i].HGPId);
  25.             this.comboBox3.Items.AddRange(so);
  26.             this.comboBox3.SelectedIndex = 0;
  27.         }

来自博客:
http://www.cnblogs.com/Caceolod/articles/1008983.html


上一篇:如何保护工业物联网(IIoT)安全


下一篇:Android零基础入门第51节:进度条ProgressBar