How to insert a blank line in a combo box filled with linq?

I have a list of elements specified by Linq from a DB. Now I filled ComboBox with this list.

How can I get an empty string in it?

My problem is that the list of values ​​is not allowed to be null, so I cannot easily add a new empty element.

+3
source share
3 answers

Can you try:

Dropdown.Items.Insert(0, String.Empty)

Another bit of success that I had was to create an empty element and insert it at the beginning of my data source before I snap to the drop-down list.

+3
source

Concat() . , Enumerable.Repeat():

list.DataSource = Enumerable.Repeat(new Entity(), 1)
                 .Concat(GetEntitiesFromDB());

( singleton 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());
+5

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, "");

Always set AppendDataBoundItems="True", because the property AppendDataBoundItemsallows you to add items to the ListControl before data binding. After data binding, the collection of elements contains both elements from the data source and previously added elements.

+1
source

Source: https://habr.com/ru/post/1719747/


All Articles