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= comboBox1.SelectedItem as User; if (user != null) { MessageBox.Show(String.Format("id={0},name={1}", user.ID, user.Name)); } } } }
转: https://www.cnblogs.com/huiy/p/14313336.html