Home > ASP.NET > ASP.NET – Create controls dynamically in asp.net and preserving the controls and their values on post back using Hidden Field . [Part I]

ASP.NET – Create controls dynamically in asp.net and preserving the controls and their values on post back using Hidden Field . [Part I]

Hi Geeks,

Many times while working with ASP.NET Web forms we come across the situation where  we need to add the controls like Text Box,labels dynamically.

In this post we will see an example where we add multiple Text Box control dynamically to the Web Form.

Suppose we  have the HTML of our Web Form as follows

 

<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">

<script type="text/javascript">
function onClickOfButton() { 

   debugger;
   var textBoxValues = "";

textBoxValues+=document.getElementById("MainContent_txtDynamic_0").value+",";

textBoxValues+=document.getElementById("MainContent_txtDynamic_1").value+",";

textBoxValues+=document.getElementById("MainContent_txtDynamic_3").value+",";

        }

    </script>
  
    <
asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
  
    <
asp:Button ID="Button1" runat="server" Text="CreateDynamic Control"   

     OnClick="Button1_Click" />

         
    <
asp:Button ID="Button2" runat="server" Text="Post" OnClick="Button2_Click"
    
OnClientClick="onClickOfButton();" />
   
    <
table id="tblDynamic" runat="server">
    </
table>

    <asp:HiddenField ID="hdField" runat="server" />
</
asp:Content>


  

  The output of the Html above is as this image

image

 

->We take input from the user , to create number of text boxes and onClick of the    CreateDynamicControl button we will add the textboxes to the tblDynamic

Code on the  CreateDynamicControl  button_Click event will be as follows

    //CreateDynamic Control click
      
protected void Button1_Click(object sender, EventArgs e)
       {
           CreateControls();
       }

       private void CreateControls()
       {
           int number_Of_Controls = Convert.ToInt32(TextBox1.Text);
           HtmlTableRow Row = new HtmlTableRow();
          
           for (int i = 0; i < number_Of_Controls; i++)
           {
               TextBox txt1 = new TextBox();
               txt1.ID = "txtDynamic_" + i.ToString();
             
               HtmlTableCell cell = new HtmlTableCell();
               cell.Controls.Add(txt1);
               Row.Cells.Add(cell);
           }
           tblDynamic.Rows.Add(Row);
       }

 

User gives input as 3 and three textboxes will be generated on click event as follows,

we insert values 11,22,33 in those fields.

image

 

Problem of Dynamic Controls on Page Post Backs :

Retrieving/Preserving the textbox values at server side on Page Post

Its very easy to create the dynamic controls but it is not that much easy to take their values at server side on post.                                                                                                                

Because,                                   

As we are creating the control dynamically they disappears when page post backs so we also need to take care of this condition and we need to re create the controls when page post backs

Solution:

->For this we have taken the Hiddenfield “hdField”  as u see in above html code                      and onPost we save the values of textboxes in the hidden filed through JavaScript function  name “onClickOfButton”

->  code on server side will be as follows

//on post click 
     
protected void Button2_Click(object sender, EventArgs e)
      {
          setValues();
      }

 
->Note the  function setValues can be called on any server side event which make page PostBack.

     private void setValues()
      {
          int number_Of_Controls = Convert.ToInt32(TextBox1.Text);
          HtmlTableRow Row = new HtmlTableRow();

//retrieving the values of textboxes

 string[] arr = hdField.Value.Split(new char[] { ‘,’ }, StringSplitOptions.RemoveEmptyEntries);
          for (int i = 0; i < number_Of_Controls; i++)
          {
              TextBox txt1 = new TextBox();
              txt1.ID = "txtDynamic_" + i.ToString();
              txt1.Text = arr[i];
              HtmlTableCell cell = new HtmlTableCell();
              cell.Controls.Add(txt1);
              Row.Cells.Add(cell);
          }
          tblDynamic.Rows.Add(Row);
      }

    

After Post Back we have our webpage as follows which shows that or dynamic controls values have been preserved after successful page postback.

image

Thanks.

Advertisements
Categories: ASP.NET
  1. Manoj Bhatt
    January 11, 2012 at 3:53 pm

    Very informative post. It’s really helpful for me and helped me lot to complete my task. Thanks for sharing with us. I had found another nice post over the internet which was also explained very well about Populate Grid Control From XML Document Easily, for more details of this post check out this link…..
    http://www.mindstick.com/Articles/08f2f90b-71e9-4a31-abf0-5131e3c19f58/?HiddenField%20Control%20in%20ASP.Net

    Thanks everyone for your precious post!!

  2. January 12, 2012 at 10:34 am

    @ Manoj Hey You are most welcome!!!

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: