Tuesday, September 27, 2011

Creating Dynamic controls in Asp.Net

Hi frnds... let us start creating dynamic controls in asp.net with a simple example of creating text boxs at runtime, After this we 'll dig into in our next example.
Firstly add a placeholder to your .aspx page like this
 <asp:PlaceHolder ID="phTextBoxes" runat="server"></asp:PlaceHolder>
now we are going to create 5 text boxes,
go to .cs file and in the method which you are trying to call for the creation of dynamic controls or in  page load write the following

 if(!IsPostBack)
{
 for (int i = 0; i <= 5; i++)
        {
                TextBox tobj = new TextBox();
                tobj.ID = "Tb" + i.ToString();
                tobj.CssClass = "tb_hello";
          }
}

Here  TextBox tobj = new TextBox(); will create a text box object for which you can give all the properties
that will be given to a general text box control created statically.
After creating a textbox control we need to add this to the placeholder That has been added to our .aspx file like this

phTextBoxes.Controls.Add(tobj);

after adding this line our code it looks as follows


if(!IsPostBack)
{


 for (int i = 0; i <= 5; i++)
        {
                TextBox tobj = new TextBox();
                tobj.ID = "Tb" + i.ToString();
                tobj.CssClass = "tb_hello";
                tobj.Visible = true;
                phTextBoxes.Controls.Add(tobj);
            }
}

All this is when the page doesn't gets PostBack, but what if the page IsPostBack...

here comes the problem, when the page gets post back the controls gets disappeared from the form.
we can solve this problem by checking weather the controls are present in the placeholder. so for that we will add the following line.

// this is for IsPostBack
if (phTextBoxes.FindControl("Tb" + i)== null)
{
-----------;
----------;
}

after adding this our code looks  like this,


 for (int i = 0; i <= 5; i++)
        {
              TextBox tobj = new TextBox();
            if (phTextBoxes.FindControl("Tb" + i)== null)
            {
                tobj.ID = "Tb" + i.ToString();
                tobj.CssClass = "tb_hello";
                tobj.Visible = true;
                phTextBoxes.Controls.Add(tobj);
            }
        }

That's all 5 textboxes will be created with style as declared in css "tb_hello" that is created in .aspx file.


Hope it 'll help someone who are starting with dynamic controls...
Read more: http://www.blogdoctor.me/2007/02/expandable-post-summaries.html#ixzz2CqUkfMpH Read more: http://www.blogdoctor.me/2007/02/expandable-post-summaries.html#ixzz2CqUBCb8r2CqUBCb8r Read more: http://www.blogdoctor.me/2007/02/expandable-post-summaries.html#ixzz2CqSEJcpq

1 comment:

  1. Nice topic about dynamic controls, can u please post me how to add file upload controls after uploading first one i want second file upload control dynamically

    ReplyDelete