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

Time:04-27

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);

CodePudding user response:

    combBox.SelectedText = "Anzeige";

    

i am using this code for displaying text on load.

CodePudding user response:

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);
  • Related