Set value of asp.net dropdownlist from codebehind

M

moondaddy

I have a asp.net dropdownlist on a page and need to set the selected item to
a certain item in the list using the codebehind. For example, I have a list
of 4 different shipping methods in the list where the value attribute is the
primary key value from the database and has nothing to do with the index of
the item I want to select. I know I can select an item like this:

Me.cmbShipMethod.Items(3).Selected = True

but I will not know the index of an item, only its PK value which might be
1233445. I could probably loop the all the list items and when I find it,
set it to that index value, but that seems klunky. Isn't there a more
elegant way to do this?
 
S

Steven Cheng[MSFT]

Hi Moondaddy,

Thanks for posting here. As for the DropDownList's Items Collection, I've
checked tha MSDN and got that its a ListItemCollection, here is the
reference in MSDN:

#ListItemCollection Class
http://msdn.microsoft.com/library/en-us/cpref/html/frlrfSystemWebUIWebContro
lsListItemCollectionClassTopic.asp?frame=true

And it has two method:
ListItemCollection.FindByText Method
and
ListItemCollection.FindByValue Method

They can help to find a certain Item in the ListItemCollection by its Text
or Value property, I think they may be helpful to you. Here are the
weblinks to their reference:

http://msdn.microsoft.com/library/en-us/cpref/html/frlrfSystemWebUIWebContro
lsListItemCollectionClassFindByTextTopic.asp?frame=true

http://msdn.microsoft.com/library/en-us/cpref/html/frlrfSystemWebUIWebContro
lsListItemCollectionClassFindByValueTopic.asp?frame=true


Regards,

Steven Cheng
Microsoft Online Support

Get Secure! www.microsoft.com/security
(This posting is provided "AS IS", with no warranties, and confers no
rights.)

Get Preview at ASP.NET whidbey
http://msdn.microsoft.com/asp.net/whidbey/default.aspx

-------------------------------------------------------------------------
 

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