zoukankan      html  css  js  c++  java
  • c# Combobox通过Item集合增加

    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;

           }

       }

    }

  • 相关阅读:
    16-高级指针
    15-C语言结构体
    14-C语言宏
    13-C语言字符串函数库
    12-C语言字符串
    11-C语言指针
    10-C语言函数
    POJ 1001 高精度乘法
    POJ 1060 多项式乘法和除法取余
    POJ 1318 字典排序
  • 原文地址:https://www.cnblogs.com/ArRan/p/2989583.html
Copyright © 2011-2022 走看看