ASP.NET DropDownList with DataSource doesn't select any item
I'm using a DropDownList
with a data source which successfully populates the list. However, I want one of the items to be selected, namely the one where the value matches the path and query of the current request.
ddlTopics.DataSource = pdc;
ddlTopics.DataBind();
foreach (ListItem item in ddlTopics.Items)
{
item.Selected = item.Value.Equals(this.Page.Request.Url.PathAndQuery);
}
Using the debugger in Visual Studio 2008 reveals that item.Selected
becomes true exactly once in the loop, but the rendered select
has no option
that is se开发者_运维知识库lected.
Any ideas?
Use
ddlTopics.SelectedValue = this.Page.Request.Url.PathAndQuery;
// Summary:
// Gets the value of the selected item in the list control, or selects the item
// in the list control that contains the specified value.
You can try this:
ddlTopics.SelectedIndex = ddlTopics.Items.IndexOf(ddlTopics.Items.FindByValue(this.Page.Request.Url.PathAndQuery));
Set theddlTopics.SelectedIndex
property to the index of the item you wanted selected.
I've always used
ddlTopics.SelectedIndex
to indicate that a row is selected, rather than assigning to the row individually.
This is how I do it...
foreach (var itm in cboOffice.Items) {
if (itm.Value == Session("office")) {
itm.Selected = true;
break; //OR EXIT FOR
}
}
精彩评论