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 月的下拉单
|