如何绑定枚举到组合框与空字段在C# [英] How to bind Enum to combobox with empty field in C#

查看:182
本文介绍了如何绑定枚举到组合框与空字段在C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将枚举值绑定到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 })
.ToList< object>();

返回数据;
}
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是一个空字符串。



<$>

解决方案

p $ p> 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); //将空字段插入到组合框中
}
return data;
}
return null;
}


How to do I bind an enum value to a ComboBox and fill it with an empty field using Linq? I have tried:

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

But I don't know how to insert the empty field into the combobox, however Key is null and Value is an empty string. Can anyone explain what I am missing?

解决方案

Try this,

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

这篇关于如何绑定枚举到组合框与空字段在C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆