ASP.NET - Adding a textbox dynamically - Asked By Simon Anderson on 13-Feb-09 06:17 PM

Hi,

In my aspx page,when a user clicks on a Location "LinkButton", a new textbox should be dynamically added in the page.
How do I achieve this functionality?

Thanks.

try this - sri sri replied to Simon Anderson on 13-Feb-09 10:09 PM

Hi,

try the following code

/////aspx page

 <asp:Panel ID="Panel1" runat="server" Height="50px" Width="125px">
        </asp:Panel>
        <asp:LinkButton ID="LinkButton1" runat="server" OnClick="LinkButton1_Click">Click Here</asp:LinkButton>


//code behind

 protected void LinkButton1_Click(object sender, EventArgs e)
    {
        TextBox txtName = new TextBox();
        txtName.ID = "txt1";
        Panel1.Controls.Add(txtName);
    }

reply - alice johnson replied to Simon Anderson on 13-Feb-09 11:46 PM

function createTXTBox()
{
        var loContentTable = document.getElementById("tblCreateTextBox"); //"tblCreateTextBox" Table id
       if(loContentTable != null)
{

for(var count=0; count < 200 ;count++)
{
var loTR = loContentTable.insertRow(loContentTable.rows.length);
if(loTR != null)
{
var loTXTBox=loTR.insertCell(0);
        if(loTXTBox!=null)
{
var contentPlace = document.getElementById("contentPlace");//contentPlace is td in the table "tblCreateTextBox"

var text12 = document.createTextNode("Auto");
var input12 = document.createElement("Input");
input12.value="auto";

input12.type="text";
loTXTBox.width="15px";

loTXTBox!.innerHTML = "<input type='text' id='count' value=tempCount onclick='javascript:doSomeThing(this)'>"

}
    }
}
     }
}

follow this step - C_A P replied to Simon Anderson on 14-Feb-09 02:22 AM

This step-by-step article describes how to dynamically create controls for an ASPX Web page.

The sample project does the following:
  • It creates two TextBox controls.
  • It verifies that the TextBox contents (TextBox.text) and attributes are saved across posts to the server.
  • It describes how events that are posted by a dynamically created control are handled.
http://support.microsoft.com/kb/317515#top

Create the Project and the Static Control

loadTOCNode(2, 'summary');
  1. In Visual Studio .NET, create a new Web project by using Visual Basic .NET. Name the project DynamicCreate.
  2. Open the WebForm1.aspx file, and then switch to HTML view. Insert the following code between the <HTML> tag and the </HTML> tag:
    <HEAD>
    <title>WebForm1</title>
    <meta name="GENERATOR" content="Microsoft Visual Studio .NET 7.0">
    <meta name="CODE_LANGUAGE" content="Visual Basic 7.0">
    <meta name="vs_defaultClientScript" content="JavaScript">
    <meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5">
    </HEAD>
    <body MS_POSITIONING="GridLayout">
    <form id="Form1" method="post" runat="server">
    <asp:Button id="Button1" style="Z-INDEX: 100; LEFT: 23px; POSITION: absolute; TOP: 108px" runat="server" Text="Submit" Height="27px" Width="100px"></asp:Button>
    <asp:Label id="Label4" style="Z-INDEX: 105; LEFT: 23px; POSITION: absolute; TOP: 197px" runat="server" Width="368px" EnableViewState="False"></asp:Label>
    <asp:Label id="Label3" style="Z-INDEX: 104; LEFT: 23px; POSITION: absolute; TOP: 163px" runat="server" Width="368px" EnableViewState="False"></asp:Label>
    <asp:Label id="Label2" style="Z-INDEX: 102; LEFT: 23px; POSITION: absolute; TOP: 60px" runat="server" Width="86px" Height="19px"> TextBox2:</asp:Label>
    <asp:Label id="Label1" style="Z-INDEX: 101; LEFT: 23px; POSITION: absolute; TOP: 28px" runat="server" Width="86" Height="19"> TextBox1:</asp:Label></form>
    </body>
  3. Switch back to Design view to see the statically created controls that the project will use.
http://support.microsoft.com/kb/317515#top

Create the Dynamic Control and Hook it Up

loadTOCNode(2, 'summary');
  1. In Solution Explorer, click Show All Files. The list of files that are associated with WebForm1.aspx appears. Open WebForm1.aspx.vb.
  2. Declare the TestBox controls in the .vb (code-behind) file. Also, declare a variable for the existing form element in the .aspx file. Update the declarations that follow the declaration for the WebForm1 public class:
    Public Class WebForm1
    Inherits System.Web.UI.Page
    Protected WithEvents Button1 As System.Web.UI.WebControls.Button
    Protected WithEvents Label4 As System.Web.UI.WebControls.Label
    Protected WithEvents Label3 As System.Web.UI.WebControls.Label
    Protected WithEvents Label2 As System.Web.UI.WebControls.Label
    Protected WithEvents Label1 As System.Web.UI.WebControls.Label

    ' Added by hand for access to the form.
    Protected Form1 As System.Web.UI.HtmlControls.HtmlForm

    ' Added by hand; will create instance in OnInit.
    Protected WithEvents TextBox1 As System.Web.UI.WebControls.TextBox
    Protected WithEvents TextBox2 As System.Web.UI.WebControls.TextBox
    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 Page_Init function that the WebForm1 class provides. Locate the Page_Init function. Expand the code that is marked with the comment "Web Form Designer generated code." Modify the Page_Init functions, so that they appear similar to the following:
    Private Sub Page_Init(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Init
    ' Create dynamic controls here.
    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)

    ' CODEGEN: The Web Form Designer requires this method call.
    ' Do not modify it by using the code editor.
    InitializeComponent()
    End Sub
    This code dynamically creates two TextBox controls, sets their IDs and positions, and then binds them to the Form Controls collection. You can also add Web Forms Panel controls to the ASPX page, and then bind the text boxes to those controls in the Page_Init function, as in the following example:
        TextBox1 = New TextBox()
    TextBox1.ID = "TextBox1"
    ' comment add command the Form Controls collection as follows
    ' Form1.Controls.Add(TextBox1)'
    Panel1.Controls.Add(TextBox1)
    Note When you create dynamic controls on a Web Form, you must create the controls and add them to the controls collection in either the Page_Init event handler or the Page_Load event handler. Otherwise, the controls may not behave as expected.
  4. Initialize the Text property for the text boxes. Modify the existing Page_Load function:
    Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    If Not IsPostBack Then
    ' Set the initial properties for the text boxes.
    TextBox1.Text = "TextBox1"
    TextBox2.Text = "TextBox2"
    End If
    End Sub
    You must set the initial value (If Not IsPostBack) of the text boxes only one time. The IPostBackDataHandler interface for the text boxes maintains this information. You do not have to reset the value for later posts.
  5. Provide a handler for the TextBox TextChanged events. Add the following code after the Page_Load function:
    Private Sub TextBox_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged, TextBox2.TextChanged
    Dim txtBoxSender As TextBox
    Dim strTextBoxID As String

    txtBoxSender = CType(sender, TextBox)
    strTextBoxID = txtBoxSender.ID

    Select Case strTextBoxID
    Case "TextBox1"
    Label3.Text = "TextBox1 text was changed"

    Case "TextBox2"
    Label4.Text = "TextBox2 text was changed"
    End Select
    End Sub
    This code verifies which control triggered the event, and then reports this to the user by using the appropriate Label control. Notice that this function handles the TextChanged event for both of the dynamically created TextBox controls. By default, AutoPostBack is false for the TextBox controls. Therefore, if a user changes the text in the controls, this action does not cause a PostBack to the server. However, when the user clicks Submit to post the form to the server, this action triggers the TextChanged events for the TextBox controls, and then this function is called.
READ THIS - C_A P replied to Simon Anderson on 14-Feb-09 02:25 AM

http://aspdotnetcodebook.blogspot.com/2008/03/how-to-create-textbox-control.html

In Technique when creating control dynamically in a Page Load event handler these controls will retain their ViewState after the PostBack, but what if controls created dynamically at runtime in a Button Click event handler instead of Page Load event then on PostBack these controls ViewState are lost.To persists the ViewState of these child controls we will recreate these controls again on a  PostBack in overrideable CreateChildControls() Method  which is called whenever

 

ASP.NET needs to create these WebControl in a Control Tree. 


// Add TextBoxes Control to Placeholder  


private void CreateTextBoxes()
  {

      for (int counter = 0; counter <= NumberOfControls; counter++)
      {
          TextBox tb = new TextBox();
          tb.Width = 150;
          tb.Height = 18;
          tb.TextMode = TextBoxMode.SingleLine;
          tb.ID = "TextBoxID" + (counter + 1).ToString();
          // add some dummy data to textboxes
          tb.Text = "Enter Title " + counter;
          phTextBoxes.Controls.Add(tb);
          phTextBoxes.Controls.Add(new LiteralControl("<br/>"));

      }

  }

In CreateTextBoxes method I loop through ā€˜nā€™ numbers of controls that we wants to create dynamically in phTextBoxes placeholder.
// Create TextBoxes on PostBack. 

protected override void CreateChildControls()
  {
      // Here we are recreating controls to persist the ViewState on every post back
      if (Page.IsPostBack)
      {
          NumberOfControls += 1;
          CreateTextBoxes();
      }
      else
      {
          CreateTextBoxes();
          // Increase the control value to 1
          NumberOfControls = 0;
      }

  }

CreateChildControls method, here we are recreating control on every

PostBack. If the page is created the first time we just create these

controls and save 1 in the ViewState so we know that we have created

these controls and assigned the controls id to 1.  

// Increase the counter when button is clicked and add to view

state  

protected void btnAddTitle_Click(object sender, EventArgs e)
  {
      NumberOfControls += 1;
  }

In button event handler we just increase the counter by 1, and save its value to ViewState
for later retrieval.Once we have created these controls on ASP.NET page, retrieving
data from these dynamically created controls is easy by using FindControl method.

// Read TextBoxes Data

public int NumberOfControls
   {
       get
       {
           if (ViewState["Count"] == null)
           {
               return 0;
           }
           return (int)ViewState["Count"];
       }
       set
       {
           ViewState["Count"] = value++;
       }
   }

   private void ReadTextBoxes()
   {
       strValue = string.Empty;
       int n = NumberOfControls;

       for (int i = 0; i <= NumberOfControls; i++)
       {

           string boxName = "TextBoxID" + (i + 1).ToString();
           TextBox tb = phTextBoxes.FindControl(boxName) as TextBox;
           strValue += tb.Text + "\n";
       

       }
       Response.Write(strValue);
   }

 

trt - jignesh shah replied to Simon Anderson on 26-Mar-09 04:33 AM
rtrtrtrt
Create TextBox Dynamically using Javascript - Asked By jignesh shah on 26-Mar-09 04:37 AM
good