0

我在页面加载时动态创建一个文本框,但问题是我无法在按钮单击时从文本框中获取值。如何从动态创建的控件中获取价值?

我的 HTML 是这样的:

<body>
    <form id="form1" runat="server">
     <asp:Button ID="Button1" runat="server" Text="Button" />


    </form>
</body>
</html>

我的代码是这样的

Partial Class TicketRound
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If (Not Page.IsPostBack) Then
            Dim tb As New TextBox
            tb.ID = "txt12"
            tb.Text = "Child "
            tb.Attributes.Add("runat", "Server")

            form1.Controls.Add(tb)
        End If
    End Sub

    Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim txtSurName As TextBox
        txtSurName = form1.FindControl("txt12")

        Response.Write(txtSurName.Text)
    End Sub
End Class
4

1 回答 1

1

您必须在每次回发时(重新)创建动态创建的控件,因此请替换:

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    If (Not Page.IsPostBack) Then
        Dim tb As New TextBox
        tb.ID = "txt12"
        tb.Text = "Child "
        tb.Attributes.Add("runat", "Server")' <-- redundant '

        form1.Controls.Add(tb)
    End If
End Sub

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    Dim tb As New TextBox
    tb.ID = "txt12"
    If Not IsPostBack Then tb.Text = "Child "
    form1.Controls.Add(tb)
End Sub

是否有任何理由动态创建此控件?

于 2013-03-28T10:22:35.783 回答