Wednesday, January 08, 2014

Combo Boxes in Windows Forms

OK, I know windows forms are viewed as ancient technology by many, but my company still uses windows forms for harnesses to test things sometimes.  It has been awhile since I used windows forms, so I ran into a slight issue in using windows forms combo boxes.

Firstly, the data binding is done slightly differently, as the combo boxes can also be bound easily to objects as well as a traditional say SQL data source.  Example of it being done in code behind on a form.

/* I got my datatable the traditional with a query to the database using a SqlDataAdapter */

mycombobox.DataSource = myDataTable;
mycombobox.DisplayMember = "description"; // your description field from your dataset
mycombobox.ValueMember = "value";  // your key field from your dataset

Slightly different mark up than the web.  Also note there is no databind() needed.

Second, getting the selected value of that combo box has a non-obvious (to me anyways) way of  getting it.  I ended up with something like this-

string selectedvalue  = ((DataRowView)mycombobox.SelectedItem).Row["value"].ToString(); //value = ValueMember

The having to cast the SelectedItem as a DataRowView makes sense when you think about it, but not something that just jumped out at me at first.

So, I hope that helps someone (including me next time I fire up an ancient windows form project).

This threat was helpful on getting the selected value

No comments: