Reputation: 7361
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.
Upvotes: 6
Views: 67114
Reputation: 1
This can be done in one statement in vb.net. Assume your dropdown list has the id of ddlYear
, could do this:
ddlYear.Items.Insert(0, New ListItem("--- All Years ---", "All"))
This inserts the new list item at position 0, or the top of the list.
Generically:
dropdownlist.items.insert(Position, New ListItem(Text, Value)
Upvotes: 0
Reputation: 21
Need to test the new list items as they are being created to see if they match the session value, then just set that one to selected and add it to the list.
Dim newListItem As ListItem
newListItem = New ListItem("Title", "Value")
if(newListItem.value == SessionValue)
newListItem.Selected = True;
salesPersonDropList.Items.Add(newListItem )
Upvotes: 0
Reputation: 1364
Store your results in an object that implements IEnumerable.
Loop through your resultset and then Loop through your DropDownList's Items collection. If the current Item is equal to the value in your result set set the Selected property to true
Say you have a populated datatable returned from your query.
Foreach(Datarow row in Datatable.Rows)
{
foreach (ListItem item in DropDownList.Items)
{
if (item.Value == row["columnName"])
{
item.Selected = true;
}
}
}
Please note that if your DropDownList's DataValueMember property is not set you will need ot use the Text property for comparison.
Upvotes: 0
Reputation: 9092
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 )
Upvotes: 11