我根据 Jason Jackson 的建议编写了这个方法:
private IEnumerable<KeyValuePair<object,object>> GetDisplayTable(DataTable dataTable, DataColumn ValueMember, string sep,params DataColumn[] DisplayMembers)
{
yield return new KeyValuePair<object,object>("<ALL>",null);
if (DisplayMembers.Length < 1)
throw new ArgumentException("At least 1 DisplayMember column is required");
foreach (DataRow r in dataTable.Rows)
{
StringBuilder sbDisplayMember = new StringBuilder();
foreach(DataColumn col in DisplayMembers)
{
if (sbDisplayMember.Length > 0) sbDisplayMember.Append(sep);
sbDisplayMember.Append(r[col]);
}
yield return new KeyValuePair<object, object>(sbDisplayMember.ToString(), r[ValueMember]);
}
}
用法:
bindingSource1.DataSource = GetDisplayTable(
/*DataTable*/typedDataTable,
/*ValueMember*/typedDataTable.IDColumn,
/*DisplayColumn Seperator*/" - ",
/*List of Display Columns*/
typedDataTable.DB_CODEColumn,
typedDataTable.DB_NAMEColumn);
comboBox1.DataSource = bindingSource1;
comboBox1.DisplayMember = "Key";
comboBox1.ValueMember = "Value";
//another example without multiple display data columns:
bindingSource2.DataSource = GetDisplayTable(
/*DataTable*/typedDataTable,
/*ValueMember*/typedDataTable.IDColumn,
/*DisplayColumn Seperator*/null,
/*List of Display Columns*/
typedDataTable.DESCColumn );
再往下,使用 Selected Value 的地方:
if (comboBox1.SelectedValue != null)
// Do Something with SelectedValue
else
// All was selected (all is my 'empty')
这将允许在 ComboBox 中显示连接的多个列,同时将 Value 成员保持为单个标识符 + 它使用带有 BindingSource 的迭代器块,对于您的情况,BindingSource 可能会过大。
欢迎评论和建议。