如何级联两个下拉列表

本文关键字:下拉列表 两个 级联 何级联 | 更新日期: 2023-09-27 18:19:04

我有一个页面,我想有两个下拉列表。当用户从第一个DDL中选择一个选项时,我希望该值确定第二个DDL中有哪些选项。下面是我的代码和标记:

Select a Category:<br />
<asp:DropDownList ID="ddlCategory" runat="server" AutoPostBack="True" 
    DataSourceID="AccessDataSource1" DataTextField="ORG_NAME" DataValueField="ID" OnSelectedIndexChanged="PopulateDDLsections">
</asp:DropDownList>
<br />
Select an Organization:<br />
<asp:DropDownList ID="ddlOrg" runat="server" 
    DataSourceID="AccessDataSource2" DataTextField="SectionName" 
    DataValueField="ID" >
</asp:DropDownList>
<asp:AccessDataSource ID="AccessDataSource2" runat="server" 
    DataFile="~/App_Data/webvideos.mdb" >
    </asp:AccessDataSource>
<asp:AccessDataSource ID="AccessDataSource1" runat="server" 
    DataFile="~/App_Data/webvideos.mdb" 
    SelectCommand="SELECT * FROM [ORGANIZATIONS]"></asp:AccessDataSource>

背后的代码:

public partial class AddRecord : System.Web.UI.Page
{

protected void Page_Load(object sender, EventArgs e)
{
}
protected void PopulateDDLsections(object sender, EventArgs e)
{
    //  orgID = Convert.ToInt32(ddlOrg.SelectedValue.ToString());
    //}
    int orgID;
    // Make sure we parse the selected value to an int.
    if (Int32.TryParse(ddlOrg.SelectedValue.ToString(), out orgID))
    {
        // Form the select statement from the orgID we just parsed.
        String command = String.Format("SELECT * FROM [ORG_SECTIONS] WHERE OrgID = {0}", orgID);
        // Assign the SelectCommand.
        AccessDataSource2.SelectCommand = command;
    }
}
}

当前在第二个DDL中没有生成任何内容。什么好主意吗?

如何级联两个下拉列表

您可以在AccessDataSource中使用ControlParameter

注意:你不需要OnSelectedIndexChanged如果你使用ControlParameter

例如

Select a Category:<br />
<asp:DropDownList ID="ddlCategory" runat="server" AutoPostBack="True"
    DataSourceID="AccessDataSource1" DataTextField="ORG_NAME" 
    DataValueField="ID">
</asp:DropDownList>
<asp:AccessDataSource ID="AccessDataSource1" runat="server"
    DataFile="~/App_Data/webvideos.mdb"
    SelectCommand="SELECT * FROM [ORGANIZATIONS]"></asp:AccessDataSource>
<br />
Select an Organization:<br />
<asp:DropDownList ID="ddlOrg" runat="server"
    DataSourceID="AccessDataSource2" DataTextField="SectionName"
    DataValueField="ID">
</asp:DropDownList>
<asp:AccessDataSource ID="AccessDataSource2" runat="server"
    DataFile="~/App_Data/webvideos.mdb"
    SelectCommand="SELECT ID,SectionName FROM ORG_SECTIONS WHERE OrgID=@OrgID ">
    <SelectParameters>
        <asp:ControlParameter ControlID="ddlCategory"
            PropertyName="SelectedValue"
            Name="ID" Type="String"
            DefaultValue="" />
    </SelectParameters>
</asp:AccessDataSource>

与SqlDataSource类似。

你的If语句在codebehind检查错误的下拉列表

更改到If以检查ddlCategory,因为它是您需要确定的第二个下拉列表