winform - comboBox
Employee
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 7 namespace WinApp03_ComboBox 8 { 9 enum EM_Department 10 { 11 开发部, 12 人事部, 13 财务部 14 } 15 class Employee 16 { 17 public int ID { get; set; } 18 public string Name { get; set; } 19 public EM_Department Department { get; set; } 20 public DateTime BirthDate { get; set; } 21 22 /// <summary> 23 /// 重写ToString()方法 24 /// </summary> 25 /// <returns>返回值: Name属性 </returns> 26 public override string ToString() 27 { 28 return this.Name; 29 } 30 } 31 }
From1
1 using System; 2 using System.Collections.Generic; 3 using System.ComponentModel; 4 using System.Data; 5 using System.Drawing; 6 using System.Linq; 7 using System.Text; 8 using System.Threading.Tasks; 9 using System.Windows.Forms; 10 11 namespace WinApp03_ComboBox 12 { 13 public partial class Form1 : Form 14 { 15 public Form1() 16 { 17 InitializeComponent(); 18 } 19 20 private void Form1_Load(object sender, EventArgs e) 21 { 22 /** 23 // 向comboBox1中添加字符串 24 comboBox1.Items.Add("Hello"); 25 comboBox1.Items.Add("World"); 26 comboBox1.Items.Add("你好,世界"); 27 // 设置默认索引 28 comboBox1.SelectedIndex = 2; 29 * */ 30 31 List<Employee> employees = new List<Employee>() 32 { 33 new Employee(){ID = 1, Name = "张三", BirthDate = new DateTime(1988,04,23), Department = EM_Department.开发部}, 34 new Employee(){ID = 2, Name = "李四", BirthDate = new DateTime(1990,10,08), Department = EM_Department.财务部}, 35 new Employee(){ID = 3, Name = "王五", BirthDate = new DateTime(1995,03,06), Department = EM_Department.人事部}, 36 new Employee(){ID = 4, Name = "赵六", BirthDate = new DateTime(1990,07,09), Department = EM_Department.开发部} 37 }; 38 39 // 绑定数据源 40 comboBox1.DataSource = employees; 41 // 显示的是数据源的Name属性 42 comboBox1.DisplayMember = "Name"; 43 // "值"字段是数据源的ID属性 44 comboBox1.ValueMember = "ID"; 45 // 设置索引,默认不选择(-1) 46 comboBox1.SelectedIndex = -1; 47 } 48 49 private void comboBox1_SelectedValueChanged(object sender, EventArgs e) 50 { 51 if ( -1 == comboBox1.SelectedIndex ) 52 { 53 label1.Text = "当前选中项索引: -1"; 54 label2.Text = "当前未选中任何项"; 55 label3.Text = "当前未选中任何项"; 56 } 57 label1.Text = "当前选中项索引: " + comboBox1.SelectedIndex.ToString(); 58 label2.Text = "当前选中项ID: " + comboBox1.SelectedValue.ToString(); 59 label3.Text = "当前选中项Name: " + comboBox1.SelectedItem.ToString(); 60 } 61 62 } 63 }