Click here to Skip to main content
15,888,162 members
Please Sign up or sign in to vote.
3.00/5 (1 vote)
Hello,

I need to know if there is a way in ASPX to auto select the first value in listbox,i've already tried to use
C#
ListBox_servidores.SelectedIndex = 0;
ListBox_servidores.Items[0].Selected = true;

but its not working, the first code selects the first item in the listbox, but at the same time when i try to use the selected item in another piece of code it looks like it is not selected.
The second code just returns an error :
SQL
Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index


Regards
Thank You
Posted
Comments
Ed Nutting 29-May-12 9:37am    
Err I think I'm being a bit obvious here but the error is saying that you have tried to access index 0 of a list but it is out or range - i.e. your list is empty...Have you actually added items to your list?
Ed
Member 8956437 29-May-12 9:44am    
Yes, i have 2 items in that list.
Ed Nutting 29-May-12 9:47am    
Have you debugged it to make sure that there are two list items in it when the code runs? No items in the list would be the only thing that would cause : ListBox_servidores.Items[0] to throw the error you are getting.
Ed
Member 8956437 29-May-12 10:03am    
I see what you mean, but when i open the web page i can see the items in the listbox, as you said, Listbox.items[0] should work correctly.
Member 8956437 29-May-12 10:09am    
Unless.. im using a listbox with a datasource selected, so it can show the values from a database, and in the aspx.cs i wrote the code above, maybe it is running the code first and then running the datasouc to add the values to the listbox.

1 solution

OP and Ed resolved the issue with comments!

Posting this to pop this one out of unanswered list.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900