Winforms Binding a ComboBox SelectedItem to an Object Property

后端 未结 1 2057
太阳男子
太阳男子 2020-12-18 11:51

I have two simple classes:

public class Customer
{
    public String CustomerID { get; set; }
    public String Forename { get; set; }
    public String Surn         


        
相关标签:
1条回答
  • 2020-12-18 12:41

    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.

    0 讨论(0)
提交回复
热议问题