views:

1614

answers:

2

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.

A: 

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<>.

Krof Drakula
+1  A: 

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.

GeekyMonkey
Pretty sure that if you add DataBind a collection you can't manually add items as well - it's an either or operation...
Matt
Not true. In your aspx file you can specify hard-coded list items, and set the attribute AppendDataBoundItems to true. Then when you do DataBind() it appends the data rows to the hard-coded items.
GeekyMonkey