编程语言
首页 > 编程语言> > C#:Combox实现key,value

C#:Combox实现key,value

作者:互联网

add方法传入的是一个object对象,利用这点可以传入一个自定义对象,选中时获得的也是一个完整对象。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WindowsFormsPassword
{
    class User
    {
        private String id;
        private String name;

        public User(String id,String name)
        {
            this.id = id;
            this.name = name;
        }

        public String ID
        {
            get
            {
                return id;
            }
            set
            {
                this.id = value;
            }
        }
        public String Name
        {
            get
            {
                return name;
            }
            set
            {
                this.name = value;
            }
        }


        //必须重写ToString方法,不然显示的是类的信息
        public override string ToString()
        {
            return this.name;
        }
    }
}
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsPassword
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            comboBox1.DropDownStyle = ComboBoxStyle.DropDownList;
            comboBox1.Items.Add(new User("1","张三"));
            comboBox1.Items.Add(new User("2", "李四"));
            comboBox1.Items.Add(new User("3", "王四"));
        }

        private void button1_Click(object sender, EventArgs e)
        {
         
           User user=(User) comboBox1.SelectedItem;
            if (user != null)
            {
                MessageBox.Show(String.Format("id={0},name={1}", user.ID, user.Name));
            }
        }
    }
}

标签:name,C#,System,value,Combox,User,using,id,String
来源: https://www.cnblogs.com/huiy/p/14313336.html