Jin Yong
Jin Yong

Reputation: 43768

how can I default selected value in asp:DropDownList

Does anyone know how can I default selected value in asp:DropDownList?

Following is my code:

<tr>
    <th align="right"><strong>Test: </strong></th>
    <td>
      <asp:DropDownList ID="Test" runat="server" DataSourceID="dsTest"
        DataValueField="TestID" DataTextField="TestName" AppendDataBoundItems="true">
        <asp:ListItem></asp:ListItem>
      </asp:DropDownList>  
      <asp:SqlDataSource ID="dsTest" runat="server" ConnectionString="<%$ ConnectionStrings:Test %>"
        SelectCommand="test_select" SelectCommandType="StoredProcedure">
      </asp:SqlDataSource>
   </td>
</tr>

How can I able to selected the display list which is the TestID is 1?

Upvotes: 4

Views: 31784

Answers (2)

Sanj
Sanj

Reputation: 3870

You have couple of options first one is below if you want to do this by default.

<asp:ListItem Selected="True"></asp:ListItem>

Or you can do this in code

Test.selectedIndex = 0;

Upvotes: 9

Abe Miessler
Abe Miessler

Reputation: 85046

Can you add it after data bind from the code behind?

<tr>
    <th align="right"><strong>Test: </strong></th>
    <td>
      <asp:DropDownList ID="Test" runat="server" DataSourceID="dsTest"
        DataValueField="TestID" DataTextField="TestName" AppendDataBoundItems="true" ondatabound="AddDefaultItem">
        <asp:ListItem></asp:ListItem>
      </asp:DropDownList>  
      <asp:SqlDataSource ID="dsTest" runat="server" ConnectionString="<%$ ConnectionStrings:Test %>"
        SelectCommand="test_select" SelectCommandType="StoredProcedure">
      </asp:SqlDataSource>
   </td>
</tr>

Then in code behind:

protected void AddDefaultItem(object sender, EventArgs e)
{
    Test.Items.Insert(0, new ListItem("", ""));
}

UPDATE:

After reading the last sentence it sounds like you might want the list item that has value 1. do do this use the code below:

Test.Items.FindByValue("1").Selected = true;

Hope one of these works for you.

Upvotes: 0

Related Questions