简体   繁体   中英

populating drop down value and item based on the selection of first drop down asp.net

It is a common question and I took hint from these two links too. Dropdown list items based on value of another drop down list

load a drop down box based on selected option in first drop down box

But none of them has provided complete solutions. I need to populate both the items along with their values.

aspx code ::

<asp:DropDownList ID="ddlFirstSelection" runat="server" AutoPostBack="true" 
    OnSelectedIndexChanged="ddlFirstSelection_SelectedIndexChanged">
    <asp:ListItem Value="0">select</asp:ListItem>
    <asp:ListItem Value="1">new record</asp:ListItem>
    <asp:ListItem Value="2">old record</asp:ListItem>
</asp:DropDownList>
 <%----- second drop down to be populated from code behind based on ddlFirstSelection selection ------%>
<asp:DropDownList ID="ddlPlan" runat="server"></asp:DropDownList>

code behind ::

protected void ddlFirstSelection_SelectedIndexChanged(object sender, EventArgs e)
        {
                if(ddlFirstSelection.SelectedValue=="1")
                {
                    ddlPlan.Items.Clear();                    
                    ddlPlan.DataTextField = "ground floor";
                    ddlPlan.DataValueField = "1";
                    ddlPlan.DataTextField = "first floor";
                    ddlPlan.DataValueField = "2";
                    ddlPlan.DataBind();
                }

        }

How to create a List to populate the ddlPlan drop down? Is there any other way rather than creating datatable for this?

You can simply create List of AnonymousType object and bind that to the DataSource of second DropDownList.

            //create list of anonymoustype
            var list = new[] 
            {
                new { Id = 1, Name = "ground floor" },
                new { Id = 2, Name = "first floor" },
            }.ToList();

            ddlPlan.Items.Clear();

            ddlPlan.DataTextField = "Name";
            ddlPlan.DataValueField = "Id";

            //bind anonymous type list to DataSource
            ddlPlan.DataSource = list;
            ddlPlan.DataBind();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM