简体   繁体   中英

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. 在此处输入图像描述

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);
    combBox.SelectedText = "Anzeige";

    

i am using this code for displaying text on load.

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

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