My Software Notes

Useful things I discover

Adding that “all” element to a combo box

leave a comment »

In the past when data binding a combo box, I’ve found that adding the “(all)” or “(none)” element to the top of the list has always seems unaesthetic to me.  A funny choice of words, you may think, but to me well written code is aesthetic and adding that top element just seemed messy. 

If you were using a data set then you had to create a row and stick it in the table in the data set and then sort the thing so your element would come to the top and then bind to the table or to the data view.

If you weren’t data binding but were loading elements in a loop, you still had to stick that “all” element in there to make sure it got on top.

Binding to a collection of objects was a bit cleaner but I still didn’t much care for it.

But now we have LINQ and at last I’ve found the aesthetic way to do it!

using (var db = new ProductDataContext())
{
    var results = from p in db.ProductTypes
                  orderby p.Description
                  select p;
    prodTypeCollection.AddRange(results.ToList());
}
//Add an "All" item to the top of the list
var all = new ProductType()
{
    ProductTypeCode = PRODUCT_TYPE_CODE_ALL,
    Description = PRODUCT_TYPE_DESCR_ALL
};
prodTypeCollection.Insert(0, all);

I like LINQ.  It is making my job a hell-uva-lot easier and more enjoyable.

Advertisements

Written by gsdwriter

June 7, 2009 at 8:56 pm

Posted in Languages, LINQ

Tagged with , ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: