public class ComboBoxItem<T>
{
private string _itemText;
public string ItemText
{
get { return _itemText; }
set { _itemText = value; }
}
private T _itemValue;
public T ItemValue
{
get { return _itemValue; }
set { _itemValue = value; }
}
public ComboBoxItem(string itemText, T itemValue)
{
this._itemText = itemText;
this._itemValue = itemValue;
}
/**/
/// <summary>
/// 確定指定的對象是否等於當前對象。
/// </summary>
public override bool Equals(object obj)
{
if (obj is ComboBoxItem<T>)
{
ComboBoxItem<T> rhs = (ComboBoxItem<T>)obj;
if (this._itemText.Equals(rhs.ItemText) && this._itemValue.Equals(rhs.ItemValue))
return true;
else
return false;
}
else
return false;
}
/**/
/// <summary>
/// 獲取當前對象的哈希代碼。
/// </summary>
public override int GetHashCode()
{
return ItemText.GetHashCode() + ItemValue.GetHashCode();
}
/**/
/// <summary>
/// 重載相等操作符
/// </summary>
public static bool operator ==(ComboBoxItem<T> lhs, ComboBoxItem<T> rhs)
{
return lhs.Equals(rhs);
}
/**/
/// <summary>
/// 重載不等操作符
/// </summary>
public static bool operator !=(ComboBoxItem<T> lhs, ComboBoxItem<T> rhs)
{
return !(lhs.Equals(rhs));
}
}
public class Student
{
private string _name;
public string Name
{
get { return _name; }
}
private int _age;
public int Age
{
get { return _age; }
}
public Student(string name,int age)
{
_name = name;
_age = age;
}
}
public Form1()
{
InitializeComponent();
List<ComboBoxItem<Student>> list = new List<ComboBoxItem<Student>>();
list.Add(new ComboBoxItem<Student>("", null));
Student s1 = new Student("Name 1", 15);
Student s2 = new Student("Name 2", 16);
list.Add(new ComboBoxItem<Student>(s1.Name, s1));
list.Add(new ComboBoxItem<Student>(s2.Name, s2));
//綁定到下拉框
comboBox1.DataSource = list;
comboBox1.DisplayMember = "ItemText";//顯示的文字
comboBox1.ValueMember = "ItemValue";//背後的對象
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (comboBox1.SelectedIndex > 0)
{
Student s = (Student)comboBox1.SelectedValue;//獲取Student對象
MessageBox.Show(s.Age.ToString());
}
}
泛型 類 ComboBoxItem
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.