Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to programmatically add a Drop down list in asp.net with specific pre-selected item

I've worked out how to create a DropDownList using the following code:

<select id="salesPersonDropList" runat="server"></select>

In my .aspx page, then my code behind loops through database output running:

Dim newListItem As ListItem
newListItem = New ListItem("Title", "Value")
salesPersonDropList.Items.Add(newListItem )

What I can't figure out is how to programatically set which of the List Items created is the one to be pre-selected in the rendered DropDownList, ie, how to create what I'd write in HTML as:

<select>
     <option value="1">1</option>
     <option selected value="2">2</option>
</select>

Based on database output. As the code behind loops through the database output it should compare the output to a session variable and if they values match, the ListItem should be the item selected in the rendered DropDown.

like image 389
Jamie Hartnoll Avatar asked Nov 30 '11 20:11

Jamie Hartnoll


1 Answers

Set your Selected property of the ListItem to true:

Dim newListItem As ListItem
newListItem = New ListItem("Title", "Value")
newListItem.Selected = True
salesPersonDropList.Items.Add(newListItem )
like image 67
MilkyWayJoe Avatar answered Nov 15 '22 06:11

MilkyWayJoe