Reputation: 3515
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
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
Reputation: 2843
Maybe in the same way after setting selected index?
if(comboBox1.SelectedIndex = -1)
{
comboBox1.SelectedIndex = 0;
selected= (CustomData)comboBox1.SelectedItem;
}
Upvotes: 2