简体   繁体   中英

Winforms Databinding Combobox reverting on lostfocus

I have an Employee object that has an EmploymentStatusID (int) field.

I have a combobox that is filled from an Employment Status enum and bound to the field in the Form_Load:

List<LookupListItem> EmpStatuses = new List<LookupListItem>();
foreach (EmploymentStatuses m in Enum.GetValues(typeof(EmploymentStatuses)))
{
    EmpStatuses.Add(new LookupListItem((int)m, m.ToString()));
}
cboStatus.DataSource = EmpStatuses; // Enum.GetValues(typeof(CommonLibrary.Lookups.EmploymentStatuses));
cboStatus.ValueMember = "ItemValue";
cboStatus.DisplayMember = "ItemDesc";
cboStatus.DataBindings.Add("SelectedValue", _presenter.SelectedOfficer, "EmploymentStatusID");

When the form comes up the correct value is displayed in the combobox, but if the user changes the value, it is set back when the combobox loses focus!

Text boxes and simple comboboxes (ie ones with a string collection) on the same form are fine.

You can see that I originally tried just using GetValues on the enum, but I changed it to a list to see if that would help. I've tried using a BindingList, I've tried using DataSourceUpdateMode.OnValidation on the binding. I even tried using cboStatus.DataBindings[0].WriteValue on the selectedindexchanged event. No matter what I do, the value changes back to what it was when the form opened! Any ideas?

i modified your code

      List<LookupListItem> EmpStatuses = new List<LookupListItem>();
        foreach (EmploymentStatuses m in Enum.GetValues(typeof(EmploymentStatuses)))
        {
            EmpStatuses.Add(new LookupListItem((int)m, m.ToString()));
        }

EmpStatuses.Add(new LookupListItem(<selectedValue>, "SomeText")); //<- my modified code

        cboStatus.DataSource = EmpStatuses; // Enum.GetValues(typeof(CommonLibrary.Lookups.EmploymentStatuses));
        cboStatus.ValueMember = "ItemValue";
        cboStatus.DisplayMember = "ItemDesc";
        // Remove this part cboStatus.DataBindings.Add("SelectedValue", _presenter.SelectedOfficer, "EmploymentStatusID");

cboStatus.SelectedValue = <selectedValue> //<- my modified code

i hope this will help :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM