Search code examples
c#asp.netsession-variablesapplication-variables

Button and DropDownList using Session/Application Variable in ASP.NET, C#


How would I implement this scenario? I have two buttons, Button1 and Button2, on the Default page. If Button1 is clicked, the contents of the DropDownList on the second page would be: a, b, and c. However, if Button2 is clicked from the Default page, the contents of the DDL on the second page would be: d and e. Thank you!


Solution

  • If you are using ASP.NET WebForms, you could populate a Session variable within your first page, with the contents being determined when either button is clicked. I would then set the DataSource for the DropDown list to the Session variable. Something like this:

    Page 1:

    protected void Button1_Click(object sender, EventArgs e)
        {
            Session["ListSource"] = new List<string>
            {
                "a",
                "b",
                "c"
            };
        }
    
        protected void Button2_Click(object sender, EventArgs e)
        {
            Session["ListSource"] = new List<string>
            {
                "d",
                "e"
            };
        }
    

    Page 2:

            protected void Page_Load(object sender, EventArgs e)
        {
            DropDownList1.DataSource = (List<string>)Session["ListSource"];
            DropDownList1.DataBind();
        }
    

    In MVC, you could have a Controller action generate the List and provide it as the model to your second page. Given you are referring to a DropDownList, though, it sounds like you are using WebForms.