dropdownlist default selected

G

Guest

How do i make a dropdownlist selected value based on the value i retrive from
the database.

Basically i have an edit page and like to display the default value in a
dropdown list from the database.

for example: if the ddl_value is 2 from the database i want the second list
item to be selected by default.


<asp:DropDownList id="ddl" runat="server">
<asp:ListItem Value="0">value 1</asp:ListItem>
<asp:ListItem Value="1">value 2</asp:ListItem> // make this dynamically
selected
<asp:ListItem Value="0">value 3</asp:ListItem>
<asp:ListItem Value="1">value 4</asp:ListItem>
</asp:DropDownList>

I am using the dropdownlist inside a repeater.. and only retriving single
record at a time based on a querystring... and using a datareader to fill the
form.

Many thanks in advance..
 
K

Ken Cox [Microsoft MVP]

Hi,

You need to find the item that has the text value "value 2" and then get its
index value. Once you have the index value, you can set the SelectedIndex to
that value.

Here's a quick way to accomplish all three:

Private Sub Page_Load _
(ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles MyBase.Load
If Not IsPostBack Then
ddl.SelectedIndex = ddl.Items.IndexOf _
(ddl.Items.FindByText("value 2"))
End If
End Sub

<asp:DropDownList id="ddl" runat="server">
<asp:ListItem Value="0">value 1</asp:ListItem>
<asp:ListItem Value="1">value 2</asp:ListItem>
<asp:ListItem Value="0">value 3</asp:ListItem>
<asp:ListItem Value="1">value 4</asp:ListItem>
</asp:DropDownList>

Does this help?

Ken
Microsoft MVP [ASP.NET]
 
C

Chris Austin

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