Click here to Skip to main content
13,193,064 members (85,117 online)
Rate this:
Please Sign up or sign in to vote.

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
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 :
Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index

Thank You
Posted 29-May-12 3:25am
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?
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.
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.
Ed Nutting 29-May-12 10:19am
Yes that makes some sense given that data loaders etc are supposed to use what's called lazy loading, only getting data when they really need to. You might want to research how to get the datasource to fill the list box immediately rather than waiting till the page renders.
Member 8956437 29-May-12 10:28am
yeah, that should fix the problem.
Member 8956437 29-May-12 10:41am
Instead of using the datasource, i did it all by code, it looks like its working correctly now.
Thanks Ed

1 solution

Rate this: bad
Please Sign up or sign in to vote.

Solution 1

OP and Ed resolved the issue with comments!

Posting this to pop this one out of unanswered list.

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

  Print Answers RSS
Top Experts
Last 24hrsThis month

Advertise | Privacy |
Web04 | 2.8.171017.2 | Last Updated 29 May 2012
Copyright © CodeProject, 1999-2017
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100