Rupert

::Me(C#,VC,MonoTouch,MonoforAndroid);

导航

c# Combobox通过Item集合增加

Posted on 2013-03-29 20:40  ArRan  阅读(1620)  评论(0编辑  收藏  举报

Combobox.Items.Add("A");//当..时添加(obj类型)

//用的时候可能非简单添加ABCD

//名称 + ID ,如省份名词+ID,但是只有1个参数

 

建立Province类并重写tostring

class Province

{

   //编写构造函数

   public Province(string id, string name)

   {

       this.Id = id;

       this.Name = name;

   }

   public string Id

   {

       get;

       set;

   }

 

   public string Name

   {

       get;

       set;

   }

   public override string ToString()

   {

       return this.Name;

   }

}

 

//添加到Combobox

Province p1 = new Province("01", "山西");

comboBox1.Items.Add(p1);

comboBox1.Items.Add(new Province("02", "山东"));

comboBox1.Items.Add(new Province("03", "广东"));

comboBox1.Items.Add(new Province("04", "广西"));

 

//可以把ID添加到数据库操作等

int n = 10;

MessageBox.Show(n.ToString());

Province obj = (Province)comboBox1.SelectedItem;

MessageBox.Show(obj.Id);

 

 

//整体代码如下

 

namespace _02关于Combox的一种绑定数据方式

{

   public partial class Form1 : Form

   {

       public Form1()

       {

           InitializeComponent();

       }

       //当窗体加载时调用

       private void Form1_Load(object sender, EventArgs e)

       {

           Province p1 = new Province("01", "山西");

           comboBox1.Items.Add(p1);

           comboBox1.Items.Add(new Province("02", "山东"));

           comboBox1.Items.Add(new Province("03", "广东"));

           comboBox1.Items.Add(new Province("04", "广西"));

       }

 

       //增加按钮,当点击按钮时显示ID

       private void button1_Click(object sender, EventArgs e)

       {

 

           int n = 10;

           MessageBox.Show(n.ToString());

           //选中相的ID,是Obj类型,转换为Province类型

           Province obj = (Province)comboBox1.SelectedItem;

           MessageBox.Show(obj.Id);

 

       }

   }

   //添加Province类

   class Province

   {

       public Province(string id, string name)

       {

           this.Id = id;

           this.Name = name;

 

       }

       public string Id

       {

           get;

           set;

       }

 

       public string Name

       {

           get;

           set;

       }

       //重写Tostring

       public override string ToString()

       {

           return this.Name;

       }

   }

}