0

I am creating a textbox dynamically on page load but the problem is that I am not able to get the value from textbox on button click. How can I get value from dynamically created control?

My HTML is like this:

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


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

My Code is like this

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 に答える