Klemen Slavič
Klemen Slavič

Reputation: 19841

DataSource containing a null value makes ComboBox fail

I've thrown myself headfirst into C# and .Net 2.0 using Linq, and I'm having a few problems debugging some of the problems, namely the following:

I have a ComboBox control (cmbObjects) I want to populate with a set of objects retrieved using Linq. I've written a helper method to populate a List<T> generic:

class ObjectProvider
{

    public static List<T> Get<T>(bool includeNull) where T : class, new()
    {
        List<T> list = new List<T>();
        LutkeDataClassesDataContext db = ConnectionManager.GetConnection();
        IQueryable<T> objects = db.GetTable<T>().AsQueryable();

        if (includeNull) list.Add(null);

        foreach (T o in objects) list.Add(o);

        return list;
    }

    public static List<T> Get<T>() where T : class, new()
    {
        return Get<T>(false);
    }
}

I verified the results when calling the function with true or false - the List does contain the right values, when passing true, it contains null as the first value, followed by the other objects.

When I assign the DataSource to the ComboBox however, the control simply refuses to display any items, including the null value (not selectable):

cmbObjects.DataSource = ObjectProvider.Get<Car>(true);

Passing in false (or no parameter) does work - it displays all of the objects.

Is there a way for me to specify a "null" value for the first object without resorting to magic number objects (like having a bogus entry in the DB just to designate a N/A value)? Something along the lines of a nullable would be ideal, but I'm kind of lost.

Also, I've tried adding new T() instead of null to the list, but that only resulted in an OutOfMemoryException.

Upvotes: 0

Views: 2816

Answers (2)

GeekyMonkey
GeekyMonkey

Reputation: 12974

The combo box control has an option to append data bound items to the hard-coded items in the list. So you hard-code your n/a value, and data bind the real values.

Upvotes: 1

Klemen Slavič
Klemen Slavič

Reputation: 19841

Okay, it seems the DataSource becomes invalid if you try to add a null value. The solution was to just add the items via a simple foreach loop with an empty string at the start instead of assigning the List<>.

Upvotes: 0

Related Questions