Skip to content

Using LINQ for Listboxes

December 20, 2007

Recently I blogged about how shitty multi-select listboxes are in winforms. 

Well, pulling your data out using LINQ as a datasouce is much less painful.  Simply throw something like this into your PageLoad

this.listBox1.DataSource = db.tGuilds.OrderBy(g => g.GuildName);

this.listBox1.ValueMember = “GuildGameID”;

this.listBox1.DisplayMember = “GuildName”;  

//and when you want to get the selected items back out you can grab them typed without all that nasty casting rubbish of old.

List<int> guildIDs = new List<int>();

//The tGuild below would have been a type object before

foreach (tGuild selection in listBox1.SelectedItems)

{

guildIDs.Add(selection.GuildGameID); //Instead of

//DataRowView drv = (DataRowView)selection;  

//guildIDs.Add(String2Int(drv.Row[1].ToString()));

}

Advertisements
No comments yet

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: