0

I am trying to create dynamic controls on button click using the following code. It creates the Textbox dynamically first time but it does not create the 2nd, 3rd or 4th etc controls. What could be the issue?

<asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
<asp:Button ID="addText" runat="server" Text="Add" onclick="addnewtext_Click" /> 

    protected int NumberOfControls
    {
        get{return (int)ViewState["NumControls"];}
        set{ViewState["NumControls"] = value;}
    }

  private void Page_Load(object sender, System.EventArgs e)
    {
        if(!Page.IsPostBack)
            this.NumberOfControls = 0;                
    }


protected void addnewtext_Click(object sender, EventArgs e)
{
        TextBox tx = new TextBox();
        tx.ID = "ControlID_" + NumberOfControls.ToString();

        PlaceHolder1.Controls.Add(tx);
        this.NumberOfControls++;
}
nav100
  • 2,923
  • 19
  • 51
  • 89
  • You're running into an [ASP.NET page life cycle](http://msdn.microsoft.com/en-us/library/ms178472(v=vs.85).aspx) issue. Put a breakpoint at the beginning of `addnewtext_Click` and look at the count of controls in PlaceHolder1. It will be zero every time. Take a look [at this answer](http://stackoverflow.com/questions/4216329/asp-net-dynamically-created-controls-and-postback). There are all kinds of questions and answers about dynamically creating controls. – j.f. Nov 04 '14 at 19:59

2 Answers2

0

When you create like this, the view state shouldn't be updated. So each time you hit the server you add one control and the others are missing. Since your place holder is at a specific location in view state adding controls to it can cause problems. When you create dynamic controls and when other static controls are created are at different times. When view state is loaded, your dynamic controls don't exist yet, but view state has data about them. Look at the below link.

Check this link out

neo
  • 1,952
  • 2
  • 19
  • 39
  • I checked the NumberofControls variable. It has the right number and it keeps the incremental value when I click on the button. – nav100 Nov 04 '14 at 18:49
0
Protected Sub btnAddContingency_Click(sender As Object, e As EventArgs)
    Dim cnt4 As Integer = Find("Contingencytxt")
        Createdynamicitem(Convert.ToString(cnt4 + 1))
End Sub



 Private Function Find(substr As String) As Integer
    Dim reqstr As String = Request.Form.ToString()
    Return ((reqstr.Length - reqstr.Replace(substr, "").Length) / substr.Length)
End Function


Protected Overrides Sub OnInit(e As EventArgs)

    Itemrecreate("Contingencytxt", "TextBox")

End Sub



Private Sub Itemrecreate(ctrlPrefix As String, ctrlType As String)
    'Dim m As Integer
    Dim ctrls As String() = Request.Form.ToString().Split("&"c)
    Dim cnt As Integer = Find(ctrlPrefix)
    If cnt > 0 Then
        For k As Integer = 1 To cnt
            For i As Integer = 0 To ctrls.Length - 1
                If ctrls(i).Contains(ctrlPrefix + k.ToString()) AndAlso Not ctrls(i).Contains("EVENTTARGET") Then
                    Dim ctrlID As String = ctrls(i).Split("="c)(0)

                    If ctrlType = "TextBox" Then

                        Createdynamicitem(k.ToString())

                    End If


                    Exit For
                End If
            Next
        Next
    End If

End Sub



Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load

    If Not IsPostBack Then
        Itemrecreate("Contingencytxt", "TextBox")
    End If

End Sub

Copy past the code

  • Why should the OP "copy this"? A **good answer** will always have an explanation of what was done and why it was done that way, not only for the OP but for future visitors to SO that may find this question and be reading your answer. – Maximilian Ast Aug 23 '16 at 08:30