asp.net 4 dropdownlist findByText not working for dynamic list
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:ListI开发者_如何学编程tem>
<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 SelectedValue
property of the dropdown: DropDownList.SelectedValue = YourValueHere;
?
Edit: I got your problem, you have to Select DropDownList Class
instead of the id of your dropdownlist control
. The code below code is working, I tested it.
ddl.SelectedIndex = ddl.Items.IndexOf(ddl.Items.FindByValue("item3"));
I've had the same problem. However in my case the dropdownlist was databound two times. 1 by myself and 1 via the parent control. After the second databound the selected index was reset.
So check if the control is databound twice.
You can also implement the selection of the item in de void yourdropdown_DataBound(object sender, EventArgs e) method. If you breakpoint this method you'll notice the databind is done twice.
You can use the below code, which works for static and dynamic values:
ddl.FindItemByText("YourText").Selected = true;
精彩评论