动态DropDownList设置Selected = true

时间:2013-01-25 01:51:21

标签: asp.net drop-down-menu

<asp:DropDownList ID="ddlOptionDependant" runat="server" AutoPostBack="True" 
  DataSourceID="sdsOptionDependant" DataTextField="product_option_name" 
  DataValueField="product_option_id" AppendDataBoundItems="True">
  <asp:ListItem Value="0" Text="None"></asp:ListItem>
</asp:DropDownList>

这个DropDownList是从Query构建的, 我需要动态检查product_option_id,当我找到匹配selected = true的匹配集时

1 个答案:

答案 0 :(得分:0)

您可以使用DropDownList的DataBound事件来实现这一点。这是一个示例..在您的aspx页面中,您需要添加OnDataBound属性,如下所示:

<asp:DropDownList ID="ddlOptionDependant" runat="server" AutoPostBack="True" 
    DataSourceID="sdsOptionDependant" DataTextField="product_option_name" 
    DataValueField="product_option_id" AppendDataBoundItems="True" 
    OnDataBound="ddlOptionDependant_DataBound">
    <asp:ListItem Value="0" Text="None"></asp:ListItem>
    </asp:DropDownList>
</asp:Content>

在你的代码背后加上这个:

protected void ddlOptionDependant_DataBound(object sender, EventArgs e)
{
    //Get the value of the ID you want to match here:
    int someId = 1;
    foreach(ListItem item in ddlOptionDependant.Items)
            item.Selected = item.Value == someId.ToString();
}

希望这有助于你