CSharp动态添加Combox项的几种方法
Posted sures
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了CSharp动态添加Combox项的几种方法相关的知识,希望对你有一定的参考价值。
1 namespace AAFormsApp1 2 { 3 public partial class Form1 : Form 4 { 5 public Form1() 6 { 7 InitializeComponent(); 8 } 9 10 private void button1_Click(object sender, EventArgs e) 11 { 12 DataTable dt = new DataTable(); 13 dt.Columns.Add("Display"); 14 dt.Columns.Add("Value"); 15 for (int i = 0; i < 5; i++) 16 { 17 DataRow dr = dt.NewRow(); 18 dr["Display"] = "显示" + i.ToString(); 19 dr["Value"] = i; 20 dt.Rows.Add(dr); 21 } 22 comboBox1.DataSource = dt; 23 comboBox1.DisplayMember = "Display"; 24 comboBox1.ValueMember = "Value"; 25 } 26 27 private void button2_Click(object sender, EventArgs e) 28 { 29 List<KeyValuePair<int, string>> cbList = new List<KeyValuePair<int, string>>(); 30 Dictionary<int, string> dic = new Dictionary<int, string>(); 31 cbList.Add(new KeyValuePair<int, string>(1, "my")); 32 cbList.Add(new KeyValuePair<int, string>(2, "is")); 33 cbList.Add(new KeyValuePair<int, string>(3, "hero")); 34 35 for (int i = 0; i < 5; i++) 36 { 37 dic.Add(i, i.ToString()); 38 } 39 comboBox1.DataSource = cbList; 40 //comboBox1.DataSource = dic; //不能是字典,这里添加会失败 41 comboBox1.DisplayMember = "Value"; 42 comboBox1.ValueMember = "Key"; 43 } 44 45 private void button3_Click(object sender, EventArgs e) 46 { 47 string[] daysOfWeek = { "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday" }; 48 comboBox1.DataSource = daysOfWeek; 49 } 50 51 private void button4_Click(object sender, EventArgs e) 52 { 53 //如果要一个一个的添加,前面不能指定DataSource,否则失败 54 string[] daysOfWeek = { "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday" }; 55 foreach (var d in daysOfWeek) 56 { 57 comboBox1.Items.Add(d); 58 } 59 //或者//comboBox1.Items.AddRange(daysOfWeek); 60 } 61 62 private void button5_Click(object sender, EventArgs e) 63 { 64 //如果要一个一个的添加,前面不能指定DataSource,否则失败 65 comboBox1.Items.Insert(0, new ComboBoxItem("0", "请选择")); 66 comboBox1.Items.Insert(1, new ComboBoxItem("1", "根目录")); 67 } 68 } 69 70 internal class ComboBoxItem : Object 71 { 72 private string _value; 73 private string _text; 74 public ComboBoxItem(string v, string t) 75 { 76 _value = v; 77 _text = t; 78 } 79 public string Text 80 { 81 get { return _text; } 82 } 83 public string Value 84 { 85 get { return _value; } 86 } 87 public override string ToString() 88 { 89 return _text; 90 } 91 92 } 93 }
以上是关于CSharp动态添加Combox项的几种方法的主要内容,如果未能解决你的问题,请参考以下文章