【问题标题】:Add empty entry to combobox bound to entity list向绑定到实体列表的组合框添加空条目
【发布时间】:2010-11-26 04:44:31
【问题描述】:

我使用绑定到实体列表 的组合框。如何在组合框中添加“未选择”条目?将 null 添加到列表会导致组合框为空。

【问题讨论】:

    标签: c# winforms entity-framework data-binding combobox


    【解决方案1】:

    您应该使用空字符串或其他唯一文本模式而不是 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;
    }
    

    【讨论】:

    • 我无法向组合框添加任何内容,因为它已绑定到实体列表。
    • 绑定后仍然可以添加事件。
    • 我无法向组合框添加任何内容,因为它已绑定到实体列表。
    • 您将一个特殊项目添加到列表,并将一个事件处理程序添加到组合框。
    • 那个特殊项应该是实体对象。那么如何创建一个虚假的实体对象呢?它应该有什么实体键?
    【解决方案2】:

    如果您绑定到 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"
    

    【讨论】:

      猜你喜欢
      • 2014-06-09
      • 1970-01-01
      • 2011-11-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多