如何级联两个DropDownLists

时间:2014-08-21 17:39:50

标签: c# asp.net

我有一个页面,我想要有两个下拉列表。当用户从第一个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中没有任何内容。有什么想法吗?

2 个答案:

答案 0 :(得分:1)

您可以使用 AccessDataSource ControlParameter

注意:如果您使用ControlParameter,则不需要 OnSelectedIndexChanged

例如,

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类似的answer

答案 1 :(得分:-1)

后面的代码中的If语句正在检查错误的下拉列表。

更改为您的If检查ddl类别,因为这是确定第二个下拉列表所需的内容。