26 Aug 2011

Adding Dynamic Textboxes

Design:
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Add Textbox" />
        <asp:Panel ID="Panel1" runat="server" >
        
        </asp:Panel> 
 
Code Behind:
Imports system.Collections.Generic
 
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
        'PreRender += New EventHandler(AddressOf _Default_PreRender)

        textboxes = New List(Of TextBox)
        If IsPostBack Then
            'recreate Textboxes
            Dim count As Integer = Int32.Parse(ViewState("tbCount").ToString())
            For i As Integer = 0 To count - 1
                Dim tb As New TextBox()
                tb.ID = "tb" & i
                Panel1.Controls.Add(tb)
                textboxes.Add(tb)
                tb.Text = Request.Form(tb.ClientID)
            Next
        Else
            ViewState("tbCount") = 0
        End If
    End Sub

    Private Sub _Default_PreRender(ByVal sender As Object, ByVal e As EventArgs)
        'remember how many textboxes we had
        ViewState("tbCount") = textboxes.Count
    End Sub

    Protected Sub Button1_Click1(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
        'create new textbox
        Dim tb As New TextBox()
        tb.ID = "tb" & Convert.ToString(textboxes.Count)
        Panel1.Controls.Add(tb)
        textboxes.Add(tb)
        ViewState("tbCount") = textboxes.Count
    End Sub 

No comments:

Post a Comment