panjo
panjo

Reputation: 3515

selected first item from combobox in winforms

I have comboBox with some items. If the user does not select anything I want to select first item from comboBox

Right now I made selection like this

var selected= (CustomData)comboBox1.SelectedItem;

of course this works only with user selection.

I know that I can set explicitly do SelectedIndex like

if(comboBox1.SelectedIndex = -1)
  comboBox1.SelectedIndex = 0;

but I don't know how to apply this to assign item to selected variable.

Upvotes: 1

Views: 3837

Answers (2)

No Idea For Name
No Idea For Name

Reputation: 11577

if you don't want duplicated code you can also connect to the selectedChanged event:

this.comboBox1.SelectedIndexChanged += new System.EventHandler(this.comboBox1_SelectedIndexChanged);

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
  {
      var selected = (CustomData)comboBox1.SelectedItem;
  }

Upvotes: 0

gregjer
gregjer

Reputation: 2843

Maybe in the same way after setting selected index?

if(comboBox1.SelectedIndex = -1)
{
  comboBox1.SelectedIndex = 0;
  selected= (CustomData)comboBox1.SelectedItem;
}

Upvotes: 2

Related Questions