Thursday, April 21, 2011

How to insert an empty row in a combobox filled by linq?

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.

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

    Kovu : This was my idea, but I cant at beginning of the combobox, only at end, can I?
  • 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.

  • 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());
    
  • Nope- throws ArgumentException

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

0 comments:

Post a Comment