带有DataSource的ASP.NET DropDownList不会选择任何项目

时间:2010-03-05 13:47:11

标签: c# asp.net data-binding

我正在使用带有数据源的DropDownList,该数据源已成功填充列表。但是,我想要选择其中一个项目,即值与当前请求的路径和查询匹配的项目。

ddlTopics.DataSource = pdc;
ddlTopics.DataBind();
foreach (ListItem item in ddlTopics.Items)
{
    item.Selected = item.Value.Equals(this.Page.Request.Url.PathAndQuery);
}

在Visual Studio 2008中使用调试器显示item.Selected在循环中只变为一次,但渲染的select没有选中option

有什么想法吗?

5 个答案:

答案 0 :(得分:2)

你可以试试这个:

ddlTopics.SelectedIndex = ddlTopics.Items.IndexOf(ddlTopics.Items.FindByValue(this.Page.Request.Url.PathAndQuery));

答案 1 :(得分:2)

使用

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.

答案 2 :(得分:0)

ddlTopics.SelectedIndex属性设置为您想要选择的项目的索引。

答案 3 :(得分:0)

我一直使用

ddlTopics.SelectedIndex

表示选择了一行,而不是单独分配给该行。

答案 4 :(得分:0)

我就是这样做的......

  foreach (var itm in cboOffice.Items) {
        if (itm.Value == Session("office")) {
            itm.Selected = true;
            break; //OR EXIT FOR
        }
    }
相关问题