WPF Databinding to a Combobox
So I’m trying to hone my skills in ASP.Net while at the same time learn new technology and languages. I’ve been working with WPF since it came out, and the more I play with it the more I like it. My most recent project includes quite a bit of databinding, which I quickly learned is very different from ASP.Net.
For this posting, I’ll assume we need to databind to a Combobox. Before I begin, please note this is of course not the only way to do this. There are numerous ways to accomplish the same result, and someone probably has a better way of doing it. This just outlines one method that works, while providing type safety.
Ok, with that out of the way, first create a public class that handles a key and a value. This is to prepare for your type safe list that the Combobox requires as its datasource. It can look as simple as this:
public class myObject
{
public int objKey {get; set;}
public string objValue {get; set;}
}
Ok, we have a class for our type safe List. Now, go get your data and put it somewhere. In my project, I read from a SQL table, put the information into a DataSet, then iterated through the DataSet adding each row to the List like so:
foreach(DataRow r in ds.Tables[0].Rows)
{
int key = Convert.ToInt32(r[0].ToString());
string value = r[1].ToString();
newObject.Add(new MakesObject {objKey = key, objValue = value });
}
Where the type safe list is named newObject. Ok, this will fill your type safe list with each object from the DataSet. Now you can bind the Combobox to the List the same way we did it in ASP.Net, only the naming changed slightly. Instead of DataSource, it’s called ItemsSource. The DataTextField and DataValueField properties are now DisplayMemberPath and SelectedValuePath. So to bind to the Combobox you can do this:
cmbMakes.ItemsSource = newObject;
cmbMakes.DisplayMemberPath = “objValue”;
cmbMakes.SelectedValuePath = “objKey”;
That’s it. You will now have your Combobox filled with your data, and the key from your database query is set to the value of each item.