Windows Develop Bookmark and Share   
 index > Windows Forms General > Setting ComboBox SelectedIndex
 

Setting ComboBox SelectedIndex

HI,

I have code like this,
ComboBox1.SelectedIndex = 0


and I am getting error below
Value of '0' is not valid for 'SelectedIndex'

How do I set the default value of combobox? (first item in the list)

Can I use the code below? what happnes if combobox doesn't have any values?
ComboBox1.SelectedIndex = ComboBox1.Items.Item(0).ToString

Thanks

netpicker9  Wednesday, July 30, 2008 7:19 PM
Using ToString() will definitly NOT work (it will not compile) since the SelectedIndex property is of type int whereas ToString() returns a string.
You get this exception because the number of Items in your combo is 0 (no items at all) and therefore you cannot select the first item (there is no first item).

hth,
Lior.
Lior Salem  Wednesday, July 30, 2008 8:00 PM
Using ToString() will definitly NOT work (it will not compile) since the SelectedIndex property is of type int whereas ToString() returns a string.
You get this exception because the number of Items in your combo is 0 (no items at all) and therefore you cannot select the first item (there is no first item).

hth,
Lior.
Lior Salem  Wednesday, July 30, 2008 8:00 PM

Lior,

How to fix this issue, can we check if combobox has any items before setting selectedindex = 0? how?

I am using the following syntax to add items to the ComboBox and then I am setting the selectedindex..
ComboBox1.Items.Add(

netpicker9  Wednesday, July 30, 2008 8:16 PM

You can use google to search for other answers

Custom Search

More Threads

• Can I make my Message Filter targetting one child form in my MDI form?
• Tip: Multiline messagebox with localized resource strings
• How to print image with print document control
• To select Image displayed in listview
• Using Process and ProcessStartInfo from Windows form - need to run on server instead
• Office Toolbar inside Internet Explorer
• How to judge two images equality?
• Fake key press
• Number Right To Left In (TreeView And DataGrid)
• Overriding ControlCollection.Add()