C# .NET - How can i add labels and textbox to .aspx page dynamically

Asked By balaji m on 11-May-11 03:24 AM
 Hi Frds,

  How can we add Labels and TextBoxes to a Panel in .aspx Page dynamically using c#?
  How can i order those Controls in an order?
  Pls Help
 

   With Regards,
   M.Balaji
dipa ahuja replied to balaji m on 11-May-11 03:40 AM
protected void Page_Load(object sender, EventArgs e)
  {
    if (!IsPostBack)
    {      
      TextBox txt = new TextBox();
      Label lbl = new Label();
      lbl.Text = "<br/>Name:";
     
      this.Page.Form.Controls.Add(lbl);
    
      this.Page.Form.Controls.Add(txt);
    }

For adding controls at proper position you can use panel and add controls on panel
Panel1.Controls.Add(lbl);
Panel1.Controls.Add(txt);
Hope this will help  you!
Reena Jain replied to balaji m on 11-May-11 04:06 AM
hi,

try following code to create the TextBox and Label controls dynamically. The controls are created every time that the page is run. The best place to do this is in the OnInit function that the WebForm1 class provides.

Locate the OnInit function. Expand the code that is marked with the "Web Form Designer generated code" comment. Modify the OnInit function so that it looks similar to the following code:

override protected void OnInit(EventArgs e)
{
  // Create dynamic controls here.
  // Use "using System.Web.UI.WebControls;"
  TextBox1 = new TextBox();
  TextBox1.ID = "TextBox1";
  TextBox1.Style["Position"] = "Absolute";
  Form1.Controls.Add(TextBox1);
 
  Label1 = new Label();
  Label1.ID = "Label1";
  TextBox2.Style["Position"] = "Absolute";
  Form1.Controls.Add(Label1);
 
  this.TextBox1.TextChanged += new System.EventHandler(this.TextBox_TextChanged);
  //
  // CODEGEN: This call is required by the ASP.NET Web Form Designer.
  //
  InitializeComponent();
  base.OnInit(e);
}

This code dynamically creates TextBox and Label controls, sets their IDs and positions, and then binds them to the Form Controls collection. The code also wires up the TextChanged events of the text box to a handler (TextBox_TextChanged).

Hope this will help you
Ravi S replied to balaji m on 11-May-11 04:24 AM
HI

Create the Dynamic Control and Hook It Up

  1. In Solution Explorer, click Show All Files to display a list of the files that are associated with WebForm1.aspx. Open the WebForm1.aspx.cs file.
  2. Declare the TextBox controls in the .cs (code-behind) file. Also, declare a variable for the existing form element in the .aspx file. Update the declarations following the declaration for the WebForm1 class:
    public class WebForm1 : System.Web.UI.Page
    {
    	protected System.Web.UI.WebControls.Label Label1;
    	protected System.Web.UI.WebControls.Label Label2;
    	protected System.Web.UI.WebControls.Label Label3;
    	protected System.Web.UI.WebControls.Label Label4;
    	protected System.Web.UI.WebControls.Button Button1;
    
    	// Added by hand for access to the form.
    	protected System.Web.UI.HtmlControls.HtmlForm Form1;
    	
    	// Added by hand; will create instance in OnInit.
    	protected System.Web.UI.WebControls.TextBox TextBox1;
    	protected System.Web.UI.WebControls.TextBox TextBox2;
    The TextBox declarations are entered by hand as they would be if a TextBox were dragged from the toolbox to the .aspx page. However, in this case, you create the controls dynamically.
  3. Add code to create the TextBox controls dynamically. The controls are created every time that the page is run. The best place to do this is in the OnInit function that the WebForm1 class provides.

    Locate the OnInit function. Expand the code that is marked with the "Web Form Designer generated code" comment. Modify the OnInit function so that it looks similar to the following code:
    override protected void OnInit(EventArgs e)
    {
        // Create dynamic controls here.
        // Use "using System.Web.UI.WebControls;"
        TextBox1 = new TextBox();
        TextBox1.ID = "TextBox1";
        TextBox1.Style["Position"] = "Absolute";
        TextBox1.Style["Top"] = "25px";
        TextBox1.Style["Left"] = "100px";
        Form1.Controls.Add(TextBox1);
    
        TextBox2 = new TextBox();
        TextBox2.ID = "TextBox2";
        TextBox2.Style["Position"] = "Absolute";
        TextBox2.Style["Top"] = "60px";
        TextBox2.Style["Left"] = "100px";
        Form1.Controls.Add(TextBox2);
    
        this.TextBox1.TextChanged += new System.EventHandler(this.TextBox_TextChanged);
        this.TextBox2.TextChanged += new System.EventHandler(this.TextBox_TextChanged);
    
        // 
        // CODEGEN: This call is required by the ASP.NET Web Form Designer.
        // 
        InitializeComponent();
        base.OnInit(e);
    }
    This code dynamically creates two TextBox controls, sets their IDs and positions, and then binds them to the Form Controls collection. The code also wires up the TextChanged events of the text boxes to a handler (TextBox_TextChanged).

    Other than setting the TextBox position programmatically and binding it to the Form Controls collection, you can add Web Forms Panel controls to the .aspx page and bind the text boxes to those in the OnInit function, similar to this:
    TextBox1 = new TextBox();
        TextBox1.ID = "TextBox1";
    //Form1.Controls.Add(TextBox1);
        Panel1.Controls.Add(TextBox1);
    Note When you create dynamic controls on a Web Form, the controls must be created and added to the controls collection either in the OnInit or in the Page_Load events. Otherwise, the controls behave unexpectedly.
  4. Initialize the Text property and styles for the text boxes. Modify the existing Page_Load function as follows:
    private void Page_Load(object sender, System.EventArgs e)
    {
        if(!IsPostBack)
        {
            // Set the initial properties for the text boxes.
            TextBox1.Text = "TextBox1";
            TextBox2.Text = "TextBox2";
        }
    }
    The initial value of the text boxes (if(!IsPostBack)) is set one time. This information is maintained by the IPostBackDataHandler interface for the text boxes, making it unecessary to reset the value for subsequent posts.
  5. Provide a handler for the TextChanged events of the TextBox control. Add the following code after the Page_Load function body:
    private void TextBox_TextChanged(object sender, System.EventArgs e)
    {
        TextBox txtBoxSender = (TextBox)sender;
        string strTextBoxID = txtBoxSender.ID;
    
        switch(strTextBoxID)
        {
            case "TextBox1":
                Label3.Text = "TextBox1 text was changed";
                break;
            case "TextBox2":
                Label4.Text = "TextBox2 text was changed";
                break;
        }
    }
refer the link
http://support.microsoft.com/kb/317794
Anoop S replied to balaji m on 11-May-11 04:27 AM

A very powerful and flexible way to program sites in ASP.NET is to one .aspx which contains a PlaceHolder control for each area of your screen. You then dynamically fill these controls during each hit of your page. This code will get you started. Notice the "FindControl" method with which you identify each control. If you want to use JavaScript on your controls, I think you have to use ClientId to access them, check it out.


<%@ Page Language="C#" %>
<script runat="server">
     
private void Page_Load(object sender, System.EventArgs e)
    {
      //build placeholder
      for(int x = 0; x <= 10; x++) {
        Label title = new Label();
        title.Text = "Item " + x.ToString();
        title.ID = "Item" + x.ToString();
        Area1.Controls.Add(title);
        Area1.Controls.Add(new LiteralControl("<br>"));
      }  
    }    
     
    private void ButtonChange_Click(object sender, System.EventArgs e)
    {
      ((Label)(Area1.FindControl("Item" + txtId.Text.ToString()))).Text = txtName.Text.ToString();

    }
</script>
<html>
  <head>
  </head>
  <body>
    <form id="Form1" method="post" runat="server">
      <P>
        <asp:PlaceHolder id="Area1" runat="server"></asp:PlaceHolder></P>
      <P> </P>
      <P>ID:
        <asp:TextBox id="txtId" runat="server" Width="51px"></asp:TextBox></P>
      <P>New Name:
        <asp:TextBox id="txtName" runat="server"></asp:TextBox></P>
      <P>
        <asp:Button id="ButtonChange" onclick="ButtonChange_Click" runat="server" Text="Change"></asp:Button></P>
      <P> </P>
    </form>
  </body>
</html>

TSN ... replied to balaji m on 11-May-11 04:29 AM
hi..

In the code behind..

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page  {

    protected override void CreateChildControls(){

        // Add a Label to the current ControlCollection.
        Label lbl = new Label();
        lbl.Text = "Label text";
        placeholder.Controls.Add(lbl);

        // Create a text box control, set the default Text property, and add it to the ControlCollection.
        TextBox box = new TextBox();
        box.Text = "Textbox text";
        placeholder.Controls.Add(box);

    }

}


in the .aspx file

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Test Website</title>
</head>
<body>
    <form id="form1" runat="server">

    <div>
    <!-- here you can place the static text and other elements -->
        <h1>TESTING</h1>
        blah blah blah blah blah
    </div>

    <div id="placeholder" runat="server">
    <!-- here is where the dinamically created elements will be placed -->
    </div>

    </form>
</body>
</html>
hoope this helps you..
Riley K replied to balaji m on 11-May-11 04:30 AM
Create an instance of the control and set its properties, as shown in the following example:


Label myLabel = new Label();
myLabel.Text = "Sample Label";



Add the new control to the Controls collection of a container already on the page, as shown in the following example:


Panel Panel1= new Panel();
Panel1.Controls.Add(myLabel);

To arrange order

You have a few options:

  1. Add additional controls such as a http://www.google.com/search?hl=en&q=asp.net%2Bliteral%2Bcontrol&aq=1&oq=ASP.Net%2Bliter Control where the text is the HTML you want such as a <BR/> tag or nbsp; in between the controls that have been added.
  2. Have multiple Placeholder controls for each appropriate section.
  3. Use CSS to position the controls where you want them. I am not a CSS expert but this can be done but it requires an understanding of CSS positioning.
  4. Add the controls into a parent control such as a table so you can add the controls into a tabel cell within a row. It would mean creating Rows and Cells to add to the table but it would give you more control over the layout.

Hope this gives you a few ideas that can help.