Thursday, February 2, 2012

dynamic dropdownlist and get selected value on postback in asp net C#

In the previous example i explained how to create DynamicDropDownList in ASP.Net

creating dynamic dropdownlist and applying cssclass in asp net C#

Now i will explain how to create and retrive selected values in postback in this post.
The dropdownlists will create to a panel as shown in the image below.

In the Page_Load write this code

          if (!Page.IsPostBack)
            this.NumberOfControls = 5;
        else
        {
            createDDL();
        }



Now to create a DynamicDropDownList write this method in the codeBehind file


    private void createDDL()
    {
        try
        {
            int count = this.NumberOfControls;
            for (int i = 0; i < count; i++)
            {
                DropDownList ddl = new DropDownList();
                ddl.ID = "ddl1" + i;
                ddl.Items.Add(new ListItem("1 year(s)", "1"));
                ddl.Items.Add(new ListItem("2 year(s)", "2"));
                ddl.Items.Add(new ListItem("3 year(s)", "3"));
                ddl.Items.Add(new ListItem("4 year(s)", "4"));
                ddl.Items.Add(new ListItem("5 year(s)", "5"));
                ddl.Items.Add(new ListItem("6 year(s)", "6"));

                Panel1.Controls.Add(ddl);
                Label lbl = new Label();
                lbl.ID = "lbl" + i;
                lbl.Text = "<br/><br/>";
                Panel1.Controls.Add(lbl);
                ddl.Visible = true;               
            }
        }
        catch (Exception ex)
        {
            string ErrMsg = ex.Message;
        }
    }

In the  above code a dynamic label is created to show some gap between newly created dropdownlist.
Just for a better appearance.

But in the postBack the selected values cannot be retrieved. So to retrieve the selected values we will use ViewState as shown below.

    protected int NumberOfControls
    {
        get { return (int)ViewState["NumControls"]; }
        set { ViewState["NumControls"] = value; }
    }    

With the help of the above code we can retrieve selected values in the page postback.
For our convenience let us add one Button and a label in the .aspx page. This label is used to show the selected values from the dropdownlists.

write this code in the button1_Click event

            Label1.Text = "";
            int count = this.NumberOfControls;
            for (int i = 0; i < count; i++)
            {
                DropDownList ddlSelected = (DropDownList)Panel1.FindControl("ddl1" + i);
                Label1.Text += ddlSelected.SelectedValue.ToString();
            }

and Finally the image looks like this


No comments:

Post a Comment