按钮点击创建动态控件

时间:2014-11-04 18:45:01

标签: asp.net

我正在尝试使用以下代码在按钮单击上创建动态控件。它首次动态创建文本框,但它不会创建第二个,第三个或第四个等控件。可能是什么问题?

<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++;
}

2 个答案:

答案 0 :(得分:0)

如果您这样创建,则不应更新视图状态。因此,每次点击服务器时,都会添加一个控件,而其他控件则丢失。由于您的占位符位于视图状态中的特定位置,因此向其添加控件可能会导致问题。创建动态控件时以及何时创建其他静态控件时。加载视图状态时,您的动态控件尚不存在,但视图状态包含有关它们的数据。请看下面的链接。

Check this link out

答案 1 :(得分: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

复制代码