C# WinForm ComboBox 自定義數據項 (ComboBoxItem )
WinForm下的ComboBox默認是以多行文本來設定顯示列表的, 這通常不符合大家日常的應用, 因爲大家日常應用通常是鍵/值對的形式去綁定它的. 那麼用鍵值對的形式如何做? 因爲Combox的每一個項的值是一個object, 實際上就是一個鍵/值對. 我用的是下面這個類的實例作爲它的一個項: /// <summary> /// ComboBox的項 /// </summary> class ListItem : System.Object { private string m_sValue = string.Empty; private string m_sText = string.Empty; /// <summary> /// 值 /// </summary> public string Value { get { return this.m_sValue; } } /// <summary> /// 顯示的文本 /// </summary> public string Text { get { return this.m_sText; } } public ListItem(string value, string text) { this.m_sValue = value; this.m_sText = text; } public override string ToString() { return this.m_sText; } public override bool Equals(System.Object obj) { if (this.GetType().Equals(obj.GetType())) { ListItem that = (ListItem)obj; return (this.m_sText.Equals(that.Value)); } return false; } public override int GetHashCode() { return this.m_sValue.GetHashCode(); ; } } 通過這個類就可以定義ComboBox的值了, 首先我們定義一個ListItem的清單作爲ComboBox的數據源: List<ListItem> items = new List<ListItem>(); items.Add(new ListItem("0", "Item_0_Text")); items.Add(new ListItem("1", "Item_1_Text")); items.Add(new ListItem("2", "Item_2_Text")); items.Add(new ListItem("3", "Item_3_Text")); items.Add(new ListItem("4", "Item_4_Text")); items.Add(new ListItem("5", "Item_5_Text")); 然後進行相應的設置: //將數據源的屬性與ComboBox的屬性對應 drpTest.DisplayMember = "Text"; //顯示 drpTest.ValueMember = "Value"; //值 然後進就可以進行綁定了: drpTest.DataSource = items; //綁定數據 綁定數據之後, 就可以對其進行默認選擇項的設置, 取值等操作: drpTest.SelectedValue = "4"; //設定選擇項 //取得當前選擇的項 ListItem selectedItem = (ListItem)drpTest.SelectedItem; string value = selectedItem.Value; //值 string text = selectedItem.Text; //顯示的文字 其他操作大家就依樣畫葫蘆吧. 呵呵. View Code
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; namespace WindowsFormsApplication3 { public partial class Form3 : Form { public Form3() { InitializeComponent(); } public struct ComboBoxItem<TKey, TValue> { private TKey key; private TValue value; public ComboBoxItem(TKey key, TValue value) { this.key = key; this.value = value; } public TKey Key { get { return key; } } public TValue Value { get { return value; } } public override string ToString() { return Value.ToString(); } } private void Form3_Load(object sender, EventArgs e) { //KeyValuePair<int, string> keys = new KeyValuePair<int,string>(); this.comboBox1.Items.Add(new ComboBoxItem<int, string>(1, "Lin")); } private void comboBox1_SelectedIndexChanged(object sender, EventArgs e) { var item = (ComboBoxItem<int, string>)this.comboBox1.SelectedItem; Text = item.Value; } } }
一個 1月 到12 月的下拉單
for (int i = 1; i <= 12; i++) { this.comboBox1.Items.Add( new ComboBoxItem<int, string>(i, String.Concat(i.ToString().PadLeft(2, '0'), "月"))); } |
---|