Wednesday, July 8, 2009

Create Dynamic DropDownList

1. Create a DynamicDropDownlist.aspx and place a placeholder and two buttons with name btnCreate and btnRetrieve. 



<asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
<
asp:Button ID="btnCreate" runat="server" Text="Create DropDownList" />
<
asp:Button ID="Retrieve" runat="server" Text="Button" onclick="btnRetrieve_Click" />


2. Create a class level Control variable and assign null to it.


Control cause = null;

3. Create CreateDropDownListControl method. This method will create dropdownlist, copy and paste below code.



public static Control GetPostBackControl(Page page)
{
      Control control = null;
      
string ctrlname = page.Request.Params.Get("__EVENTTARGET");
      
if (ctrlname != null && ctrlname != string.Empty)
      {
            control = page.FindControl(ctrlname);
      }
      
else
      
{
            
foreach (string ctl in page.Request.Form)
            {
                  Control c = page.FindControl(ctl);
                  
if (c is System.Web.UI.WebControls.Button)
                  {
                        control = c;
                        
break;
                  }
            }
      }
      return control;
}


4. Create Page_Init method, copy and paste below code.


protected void Page_Init(object sender, EventArgs e)
{
      if (IsPostBack)
      {
            //Method to get the control which caused postback
            
cause = GetPostBackControl(Page);
            
//To make sure new dropdownlist get create on click of
create DropDownList
            
if (cause != null && cause.ID.Equals("btnCreate"))
            {
                  CreateDropDownListControl();
            }
            
//To re-create control in case of any postback excluding click of Create DropDownList
            
else if (cause == null || !cause.ID.Equals("btnCreate"))
            {
                  CreateDropDownListControl();
            }
      }
}

5. OnSelectedIndexChanged method will return value of the selected dropdownlist index,Copy and paste below code. 



protected void OnSelectedIndexChanged(object sender, EventArgs e)
{
      DropDownList ddl = (DropDownList)sender;
      Response.Write(ddl.SelectedItem.Text);
}


6. btnRetrieve_Click method will return value of the all selected dropdownlist index,Copy and paste below code.



protected void btnRetrieve_Click(object sender, EventArgs e)
{
      int ddlCount = Convert.ToInt32(Session["Count"].ToString());
      for (int i = 0; i < ddlCount; i++)
      {
            Response.Write(
"Selected Dropdownlist values are " + Request.Form["ddl" + i.ToString()] + "</br>");
      }
}


Lets' put all together in DynamicDropDownlist.aspx.cs file.



using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;






public partial class DynamicDropDownlist : System.Web.UI.Page
{
      Connrol cause = null;
      
protected void Page_Init(object sender, EventArgs e)
      {
            
if (IsPostBack)
            {
                  
//Method to get the control which caused postback
                  cause = GetPostBackControl(Page);
                  
//To make sure new dropdownlist get create on click of Create DropDownList
                  
if (cause != null && cause.ID.Equals("btnCreate"))
                  {
                        CreateDropDownListControl();
                  }
                  
//To re-create control in case of any postback excluding click of Create DropDownList
                  
else if (cause == null || !cause.ID.Equals("btnCreate"))
                  {
                        CreateDropDownListControl();
                  }
            }
      }
      public static Control GetPostBackControl(Page page)
      {
            
Control control = null;
            
string ctrlname = page.Request.Params.Get("__EVENTTARGET");
            
if (ctrlname != null && ctrlname != string.Empty)
            {
                  control = page.FindControl(ctrlname);
            }
            
else
            
{
                  
foreach (string ctl in page.Request.Form)
                  {
                        
Control c = page.FindControl(ctl);
                        
if (c is System.Web.UI.WebControls.Button)
                        {
                              control = c;
                              
break;
                        }
                  }
             }
             
return control;
      }

      protected void Page_Load(object sender, EventArgs e)
      {
      }




      protected void btnRetrieve_Click(object sender, EventArgs e)
      {
            
int ddlCount = Convert.ToInt32(Session["Count"].ToString());
            for (int i = 0; i < ddlCount; i++)
            {
                  Response.Write(
"Selected Dropdownlist values are " + Request.Form["ddl" + i.ToString()] + "</br>");
            }
      }


      protected void CreateDropDownListControl()
      {
            
if (Session["Count"] == null)
            {
                  
DropDownList ddl = new DropDownList();
                  ddl.ID =
"ddl0";
                  ddl.AutoPostBack =
true;
                  ddl.Items.Add(
new ListItem("Test0", "0"));
                  ddl.Items.Add(
new ListItem("Test1", "1"));
                  ddl.SelectedIndexChanged +=
new EventHandler
OnSelectedIndexChanged);
                  PlaceHolder1.Controls.Add(ddl);
                  Session[
"Count"] = "1";
            }
            
else
            
{
                  
int ctrlCount = 0;
                  
if (cause != null && cause.ID.Equals("btnCreate"))
                  {
                        
ctrlCount =
Convert.ToInt32(Session["Count"].ToString()) + 1;
                        Session[
"Count"] = (Convert.ToInt32(Session["Count"].ToString()) + 1).ToString();
                  }
                  
else
                  
{
                        ctrlCount =
Convert.ToInt32(Session["Count"].ToString());
                  }
                  
for (int i = 0; i < ctrlCount; i++)
                  {
                        
DropDownList ddl = new DropDownList();
                        ddl.ID =
"ddl" + i.ToString();
                        ddl.AutoPostBack =
true;
                        ddl.Items.Add(
new ListItem("Test" + i.ToString(), "0"));
                        ddl.Items.Add(
new ListItem("Test" + (i + 1).ToString(), "1"));
                        ddl.SelectedIndexChanged +=
new EventHandler(OnSelectedIndexChanged);
                        PlaceHolder1.Controls.Add(ddl);
                  }
            }
      }




      protected void OnSelectedIndexChanged(object sender, EventArgs e)
      {
            DropDownList ddl = (DropDownList)sender;
            Response.Write(ddl.SelectedItem.Text);
      }


}


Happy Coding :)

1 comment:

Unknown said...

Gracias. Tu aporte esta excelente

Site Meter