我有一个项目列表,由Linq从DB中给出。 现在我用这个列表填充了一个ComboBox。
我怎么能得到一个空行?
我的问题是,在列表中,值不允许为空,因此我无法轻松添加新的空项。
答案 0 :(得分:5)
您可以使用Concat()在静态项目后追加您的实际数据。你需要创建一个空项的序列,你可以使用Enumerable.Repeat():
list.DataSource = Enumerable.Repeat(new Entity(), 1)
.Concat(GetEntitiesFromDB());
或者通过定义一个简单的扩展方法(在集合论中,单例是一个基数为1的集合):
public IEnumerable<T> AsSingleton<T>(this T @this)
{
yield return @this;
}
// ...
list.DataSource = new Entity().AsSingleton().Concat(GetEntitiesFromDB());
甚至更好,编写一个Prepend方法:
public IEnumerable<T> Prepend<T>(this IEnumerable<T> source, params T[] args)
{
return args.Concat(source);
}
// ...
list.DataSource = GetEntitiesFromDB().Prepend(new Entity());
答案 1 :(得分:3)
你能尝试这样做吗?
Dropdown.Items.Insert(0, String.Empty)
我获得的另一个成功是创建一个空项并在我绑定到下拉列表之前将其插入数据源的开头。
答案 2 :(得分:1)
Aspx Page
<asp:DropDownList ID="DDL" runat="server" AppendDataBoundItems="True">
<asp:ListItem Selected="True" Value="0" Text=""></asp:ListItem>
</asp:DropDownList>
C#Page
Dropdown.Items.Insert(0, "");
始终设置AppendDataBoundItems="True"
,因为AppendDataBoundItems
属性允许您在数据绑定发生之前将项添加到ListControl对象。数据绑定后,items集合包含数据源中的项目和以前添加的项目。