ComboBox SelectedIndex

  • Thread starter Thread starter jim
  • Start date Start date
J

jim

How do I immediately set the SelectedIndex of a combobox
(dropdownlist) upon Form Load?

I'm getting out of range errors and I suspect it's due that the Form
has not been displayed yet.

Please help.. thanks.
 
It depends on when your combobox is loaded. If you are simply adding the
items at designtime via the combobox' Items property, then they should all
be available in the Form's Load event so this should work..

private void Form1_Load(object sender, System.EventArgs e)
{
if (comboBox1.Items.Count > 0)
comboBox1.SelectedIndex = 0;
}

Otherwise, remember that the items list is zero based. If you want to
select the last item in the list, you need to do it like this..

private void Form1_Load(object sender, System.EventArgs e)
{
if (comboBox1.Items.Count > 0)
comboBox1.SelectedIndex = comboBox1.Items.Count - 1;
}

because "comboBox1.Items.Count" *IS* out of range.
 
Back
Top