ComboBox SelectedIndex

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.
 
L

Leit Rachsor

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top