1

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.

musigh
  • 167
  • 1
  • 3
  • 13
  • With `Enum.GetValues(typeof(StateType));` you have an Array of `StateType` members. So, each Item in the ComboBox is a `StateType` object. You cannot set the `ValueMember` (there's not named selector, so neither `DisplayMember` can be set). The display value is `[StateType].ToString()`. If you want to select an item with one of the values of the Enumerator, cast the `int` value to `StateType`: `cmbxType.SelectedItem = (StateType)2`. You should, in this case, validate the value with `if Enum.IsDefined(typeof(StateType), 2) (...)`. – Jimi Jul 20 '19 at 20:27

1 Answers1

1

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());
        }
    }
}
Marius
  • 1,529
  • 6
  • 21