如何在C#中将Enum与空字段绑定到组合框

时间:2013-12-14 08:17:12

标签: c# combobox enums

如何将枚举值绑定到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为空字符串。谁能解释我错过的东西?

1 个答案:

答案 0 :(得分:2)

试试这个,

    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;
    }