Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
630 views
in Technique[技术] by (71.8m points)

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

I have two 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 then create a 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 I have a combo box, against which I set the data source to be my list of Customers, and the DisplayMember to be the Forename property of the Customer object:

comboBox1.DisplayMember = "Forename";
comboBox1.DataSource = customers;

And the result is a combo box with two items, "John" and "Jeremy". Up to now I'm not too confused.

What I would like to be able to do though, is set the "OrderedBy" property of an instance of Order, based on the selection from the Combobox - Can complex types be bound to ComboBoxes like this?

I've tried this, but it doesnt seem to be updating the OrderedBy property of the Order instance:

Order myOrder = new Order();
comboBox1.DataBindings.Add("SelectedItem", myOrder, "OrderedBy");

I dont know if what I'm trying to do is possible, or if it is beyond the capabilities of Data Binding in WinForms.

I'd like to avoid having to update my Order object as part of an event handler on the ComboBox, and solely use Data Binding if possible.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your code will update a property of the bounded object, but only after ComboBox loses focus.

If you want to update the property straight after the SelectedItem changed, the fastest approach will be to send a message about changes manually.
In a ComboBox, when the SelectedItemchanges, it will fire the SelectionChangesCommitted event.

You can create an event handler to take care of the change and manually call the binding:

private void combobox1_SelectionChangesCommitted(Object sender, EventArgs e)
{
    ((ComboBox)sender).DataBindings["SelectedItem"].WriteValue();
}

You could also use the ComboBox.ValueMember property and bind your object property to the SelectedValue.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...