I have a dropdownlist, whose datasource is from SQL server.
<asp:DropDownList ID="State" runat="server" DataSourceID="SqlDataSource1" DataTextField="STATE_NAME" DataValueField="STATE_FIPS">
</asp:DropDownList>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="SELECT DISTINCT [STATE_NAME], [STATE_FIPS] FROM [county] order by [STATE_NAME]">
</asp:SqlDataSource>
I want to prepopulate the value in the list. i use DropDownList.SelectedIndex = DropDownList.Items.IndexOf(DropDownList.Items.FindByValue(YourValueHere)). but it’s not working. it gives me a null from DropDownList.Items.FindByValue(YourValueHere).
The same code works fine if i use static listitem, like:
<asp:DropDownList ID="ddl" runat="server">
<asp:ListItem>item1</asp:ListItem>
<asp:ListItem>item2</asp:ListItem>
<asp:ListItem>item3</asp:ListItem>
<asp:ListItem>item4</asp:ListItem>
</asp:DropDownList>
Any ideas? Thanks!
What about directly using the
SelectedValueproperty of the dropdown:DropDownList.SelectedValue = YourValueHere;?Edit: I got your problem, you have to Select
DropDownList Classinstead of theid of your dropdownlist control. The code below code is working, I tested it.