tags:

views:

291

answers:

4

I have a list of Items, given by Linq from the DB. Now I filled a ComboBox with this list.

How I can get an empty row in it?

My problem is that in the list the values aren't allowed to be null, so I can't easily add a new empty item.

A: 

Can't you add an empty Item to the ComboBox after the bind?

David Basarab
This was my idea, but I cant at beginning of the combobox, only at end, can I?
Kovu
+1  A: 

Can you try doing this:

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

The other bit of success I've had is to create an empty item and insert it at the beginning of my datasource before I bind to the dropdown.

brentkeller
+1  A: 

You can use Concat() to append your real data after the static item. You'll need to make a sequence of the empty item, which you can do with Enumerable.Repeat():

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

Or by defining a simple extension method (in set theory a singleton is a set with cardinality 1):

public IEnumerable<T> AsSingleton<T>(this T @this)
{
    yield return @this;
}

// ...
list.DataSource = new Entity().AsSingleton().Concat(GetEntitiesFromDB());

Or even better, write a Prepend method:

public IEnumerable<T> Prepend<T>(this IEnumerable<T> source, params T[] args)
{
    return args.Concat(source);
}


// ...
list.DataSource = GetEntitiesFromDB().Prepend(new Entity());
dahlbyk
+1  A: 

Nope- throws ArgumentException

"Items collection cannot be modified when the DataSource property is set."

BubbaHoTep