我使用绑定到List<>的ComboBox实体。如何在组合框中添加“未选中”条目?将null添加到列表会导致空组合框。
答案 0 :(得分:7)
如果您绑定到IEnumerable
实体列表,您当然可以手动添加空对象。
例如
var qry = from c in Entities
select c;
var lst = qry.ToList();
var entity = new Entity();
entity.EntityId= -1;
entity.EntityDesc = "(All)";
lst.Insert(0, entity);
MyComboBox.DataSource = lst;
MyComboBox.DisplayMember = "EntityDesc"
MyComboBox.ValueMember = "EntityId"
答案 1 :(得分:2)
您应该使用空字符串或其他唯一文本模式而不是null。
然后您可以处理Combobox的Format事件以拦截<empty>
并显示替代文本。
private void comboBox1_Format(object sender, ListControlConvertEventArgs e)
{
e.Value = FormatForCombobox(e.ListItem);
}
private string FormatForCombobox(object value)
{
string v = (string) value;
if (v == string.Empty)
v = "<no Selection>";
return v;
}