musigh
musigh

Reputation: 175

Not able to set "SelectedValue" in Combobox bound with enum

I want to set default value (rather than first one) in combobox through SelectedItem/SelectedText/SelectedValue (from any one way).

I have tried to resolve it through many different ways. Like I have set enum to Key Value Pair. Tried to use "SelectedIndex". It is showing '-1' while debugging. In other "selected*" options, value is 'null'. I do not know what is happening. I have attached code. Please take a look and help me to resolve it. Thank you.

            ComboBox cmbxType= new ComboBox();
            cmbxType.FormattingEnabled = true;
            cmbxType.DropDownStyle = ComboBoxStyle.DropDownList;
            cmbxType.Margin = new Padding(3, 6, 3, 3);
            cmbxType.Name = "cmbxType";
            cmbxType.Size = new System.Drawing.Size(200, 28);
            cmbxType.TabIndex = 1;
            cmbxType.DataSource = Enum.GetValues(typeof(StateType));
            cmbxType.SelectedIndexChanged += new System.EventHandler(cmbxType_SelectedIndexChanged);
            cmbxType.ValueMember = (workflowRows).ToString();
            cmbxType.SelectedValue = 2

PS: I am creating this combobox after creating form and the problematic case is with enum only.

Upvotes: 1

Views: 274

Answers (1)

Marius
Marius

Reputation: 1679

According to this Stack Overflow question you can only set the selected item after the data bindings are assigned. If you select the item when the OnLoad event occures it should work. Below is a working example.

using System;
using System.Windows.Forms;

namespace WindowsFormsApp
{
    static class Program
    {
        internal enum StateType
        {
            State1, 
            State2, 
            State3
        }

        internal class DemoForm : Form
        {
            ComboBox cmbxType = new ComboBox();

            public DemoForm()
            {
                cmbxType.DataSource = Enum.GetValues(typeof(StateType));
                Controls.Add(cmbxType);
            }

            protected override void OnLoad(EventArgs e)
            {
                base.OnLoad(e);
                cmbxType.SelectedItem = StateType.State3;
            }
        }

        [STAThread]
        static void Main()
        {
            Application.Run(new DemoForm());
        }
    }
}

Upvotes: 1

Related Questions