C# WinForm 技巧二: Combobox手动绑定数据
定义一个类,有两个属性
/// <summary>
/// 元数据
/// </summary>
[System.Diagnostics.DebuggerStepThrough]
[Serializable]
public class SandData
{
String key = "";
Object value = "";
/// <summary>
/// 元数据
/// </summary>
public SandData() { }
/// <summary>
/// 元数据
/// </summary>
public SandData(String m_key,Object m_value) {
this.key = m_key;
this.value = m_value;
}
public String Key
{
get { return key; }
set { key = value; }
}
public Object Value
{
get { return this.value; }
set { this.value = value; }
}
/// 元数据
/// </summary>
[System.Diagnostics.DebuggerStepThrough]
[Serializable]
public class SandData
{
String key = "";
Object value = "";
/// <summary>
/// 元数据
/// </summary>
public SandData() { }
/// <summary>
/// 元数据
/// </summary>
public SandData(String m_key,Object m_value) {
this.key = m_key;
this.value = m_value;
}
public String Key
{
get { return key; }
set { key = value; }
}
public Object Value
{
get { return this.value; }
set { this.value = value; }
}
}
然后,用一个
ArrayList list = new ArrayList();
foreach (DataRow row in table.Rows)
{
string text = row["d_name"].ToString() +"[" + row["UptownName"].ToString() + row["BuildingName"].ToString() + row["UnitName"].ToString()+"]";
string value = row["Id"].ToString();
SandData vo = new SandData();
vo.Key = text;
vo.Value = value;
list.Add(vo);
}
this.comboBox1.DataSource = list;
this.comboBox1.DisplayMember = "Key";
this.comboBox1.ValueMember = "Value";
foreach (DataRow row in table.Rows)
{
string text = row["d_name"].ToString() +"[" + row["UptownName"].ToString() + row["BuildingName"].ToString() + row["UnitName"].ToString()+"]";
string value = row["Id"].ToString();
SandData vo = new SandData();
vo.Key = text;
vo.Value = value;
list.Add(vo);
}
this.comboBox1.DataSource = list;
this.comboBox1.DisplayMember = "Key";
this.comboBox1.ValueMember = "Value";
这样就OK了,取值只要cbb.SelectedValue就取到了。