Search code examples
c#winformsdata-bindingcombobox

Initial Item in Data bound Combobox is not selected. Even though the Bound Object has a Value


I have a class which is creating a Combobox with a Databinding to an Object. The Object has a Value for an enum. But when the ComboBox is loaded it doesnt Contain a Value. The Following is the part where i´m creating the ComboBox.enter image description here

ComboBox combBox = new ComboBox();
        combBox.DropDownStyle = ComboBoxStyle.DropDownList;
        combBox.BackColor = Color.White;
        combBox.DisplayMember = "Anzeige";
        combBox.ValueMember = "Value";

        var values = Enum.GetValues(EnumType);

        foreach(int value in values)
        {
            ComboBoxItemClass comboBoxItemClass = new ComboBoxItemClass() { Value = value, Anzeige = Enum.GetName(EnumType, value) };
            combBox.Items.Add(comboBoxItemClass);
        }

        combBox.DataBindings.Add(nameof(combBox.SelectedValue), NAFDetailView.CurrentObject, PropertyName, true);

Solution

  • I solved the Problem by getting rid of the ComboBoxItemClass, and assigning the DataSource of the ComboBox, after that i used the SelectedItem Property for the DataBinding as follows.

    ComboBox combBox = new ComboBox();
    combBox.DropDownStyle = ComboBoxStyle.DropDownList;
    combBox.DataSource = Enum.GetValues(EnumType);
    combBox.DataBindings.Add(nameof(combBox.SelectedItem), NAFDetailView.CurrentObject, PropertyName, true);