c# - Winforms Binding a ComboBox SelectedItem to an Object Property -


this first attempt @ databinding in winforms, please bare me.

i have 2 simple classes:

public class customer {     public string customerid { get; set; }     public string forename { get; set; }     public string surname { get; set; } } 

and

public class order {     public string orderid { get; set; }     public decimal value { get; set; }     public customer orderedby { get; set; } } 

i create list of customer objects:

list<customer> customers = new list<customer>(); customers.add(new customer() { customerid = "1", forename = "john", surname = "smith"}); customers.add(new customer() { customerid = "2", forename = "jeremy", surname = "smith" }); 

and have combo box, against set data source list of customers, , displaymember forename property of customer object:

combobox1.displaymember = "forename"; combobox1.datasource = customers; 

and result combo box 2 items, "john" , "jeremy". i'm not confused.

what able though, set "orderedby" property of instance of order, based on selection combobox - can complex types bound comboboxes this?

i've tried this, doesnt seem updating orderedby property of order instance:

order myorder = new order(); combobox1.databindings.add("selecteditem", myorder, "orderedby"); 

i dont know if i'm trying possible, or if beyond capabilities of data binding in winforms.

i'd avoid having update order object part of event handler on combobox, , solely use data binding if possible.

cheers

your code update property of bounded object, after combobox looses focus.

if want update property straight after selecteditem changed - fastest approach send message changes manually.
in combobox changing of selecteditem fire event selectionchangescommitted.
can create event handler send message changes

private void combobox1_selectionchangescommitted(object sender, eventargs e) {     ((combobox)sender).databindings["selecteditem"].writevalue(); } 

or using use combobox.valuemember property , bound object property selectedvalue


Comments