【问题标题】:How to bind Enum to combobox with empty field in C#如何在 C# 中将枚举绑定到具有空字段的组合框
【发布时间】:2013-12-14 08:17:12
【问题描述】:

如何将枚举值绑定到 ComboBox 并使用 Linq 用空字段填充它?我试过了:

public static List<object> GetDataSource(Type type, bool fillEmptyField = false)
{
    if (type.IsEnum)
    {
         if (fillEmptyField)
         {
             var data =  Enum.GetValues(type)
                        .Cast<Enum>()
                        .Select(E => new { Key = (object)Convert.ToInt16(E), Value = ToolsHelper.GetEnumDescription(E) })
                        .ToList<object>();

             return data;
         }
         else
         {
            return Enum.GetValues(type)
              .Cast<Enum>()
              .Select(E => new { Key = Convert.ToInt16(E), Value = ToolsHelper.GetEnumDescription(E) })
              .ToList<object>();
          }
    }

    return null;
}

但我不知道如何将空字段插入组合框中,但是 Key 为 null 而 Value 为空字符串。谁能解释我错过了什么?

【问题讨论】:

    标签: c# combobox enums


    【解决方案1】:

    试试这个,

        public static List<object> GetDataSource(Type type, bool fillEmptyField = false)
        {
            if (type.IsEnum)
            {
                var data = Enum.GetValues(type).Cast<Enum>()
                           .Select(E => new { Key = (object)Convert.ToInt16(E), Value = ToolsHelper.GetEnumDescription(E) })
                           .ToList<object>();
    
                var emptyObject = new {Key = default(object), Value = ""};
    
                if (fillEmptyField)
                {
                    data.Insert(0, emptyObject); // insert the empty field into the combobox
                }
                return data;
            }
            return null;
        }
    

    【讨论】:

    • 这对我来说似乎是一种可行的方法,但问题要求 Keynull,所以它应该是 Key = (object)nullKey = default(object) 而不是 Key = -1。跨度>
    • @hvd,不错的收获。我会放默认(对象)。谢谢
    猜你喜欢
    • 2020-07-26
    • 2018-11-12
    • 2020-02-07
    • 2011-08-04
    • 1970-01-01
    • 1970-01-01
    • 2014-10-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多