Categories
.NET C#.NET VB.NET/VB WPF

WPF ComboBox: DataBinding with DataTable

Well it seems easy thing, but it took a while for me to get it working. Frankly I still don’t know why it works this way, but at least it works. With WPF I was expecting something as easy as giving DataTable object to ComboBox by it’s property and define the Data Field and Value field as in ASP.NET dropdownlist and it will bind, but this was not the case or at least the syntax is little different. So it goes like

ComboBox cb = new ComboBox(); /// You might already have object of it, so I just create it for sake of understanding here.
cb.ItemSource = MyDataTable.Rows; /// Yup, DataTable will not bind but it's rows collection will.
cb.DisplayMemberPath = ".[" + YourColumnNameVariable + "]"; ///in other other ".[columnname]" is what is expected;
cb.SelectedValuePath = ".[" + YourColumnNameVariable2 + "]"; ///in other other ".[columnname]" is what is expected;

This is all we need to do to get it working.