[C#] ComboBox和ListBox如何將顯示和值分開

5 mins.

今天在寫AP時使用了ComboBox和ListBox
想要在顯示和值是不同的
發現了另一種寫法

一種寫法是將資料放到DataTable

1
2
3
4
5
6
DataTable dt = QueryTable(sql);

ComboBox cmb = new ComboBox();
cmb.DataSource = dt;
cmb.DisplayMember = "Name";
cmb.ValueMember = "ID";

另一種寫法,自己寫一個class去存放

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
public class ObjectBindItem
{
private string mDisplay;
private string mValue;

public ObjectBindItem(string dis, string val)
{
this.mDisplay = dis;
this.mValue = val;
}

public string Display
{
get { return this.mDisplay; }
}

public string Value
{
get { return this.mValue; }
}

public override string ToString()
{
return this.mDisplay + "-" + this.mValue;
}
}

ArrayList ary = new ArrayList();
ary.Add(new ObjectBindItem("john", "A123");

ComboBox cmb = new ComboBox();
cmb.DataSource = ary;
cmb.DisplayMember = "Display";
cmb.ValueMember = "Value";