How to add textboxes, labels and buttons dynamically at runtime in VB?

后端 未结 5 1479
滥情空心
滥情空心 2021-01-06 19:25

How to create a form with a button add_subjects which adds one textbox and a corresponding label on each click,3 buttons - Add, Edit and Dele

5条回答
  •  迷失自我
    2021-01-06 19:37

    Private Property number as Integer=1
    
    Private Sub add_subject_Click(sender As Object, e As EventArgs) Handles add_subject.Click
        Dim tb As New TextBox
        tb.Name="TextBox"+number.ToString
        tb.Position = New Point(number*40,10) ' change this if you want
        Me.Controls.Add(tb)
        Dim lb As New Label
        lb.Name="Label"+number.ToString
        lb.Position = New Point(number*40,50) ' change this if you want
        Me.Controls.Add(lb)
        Dim add As New Button
        add.Name="AddButton"+number.ToString
        add.Position = New Point(number*40,100) ' change this if you want
        AddHandler(add.Click, AdressOf(add_Click))
        Me.Controls.Add(add)
        Dim edit As New Button
        edit.Name="EditButton"+number.ToString
        edit.Position = New Point(number*40,150) ' change this if you want
        AddHandler(edit.Click, AdressOf(edit_Click))'you have to make edit_Click
        YourForm.Controls.Add(edit)
        Dim delete As New Button
        delete.Name="DeleteButton"+number.ToString
        delete.Position = New Point(number*40,200) ' change this if you want
        AddHandler(delete.Click, AdressOf(delete_Click))'you have to make delete_Click
        Me.Controls.Add(delete)
        number+=1
    End Sub
    

    So we make all controls, dynamically make names, change positions, add handlers and add controls to form.

    Private Sub add_Click(sender As Object, e As EventArgs)
        Ctype(Me.Controls.Find("Label"+sender.Name.Substring(9),True).First,Label).Text = Ctype(Me.Controls.Find("TextBox"+sender.Name.Substring(9),True).First,TextBox).Text 
    End Sub
    

    Here we find Label And TextBox using sender's number(sender.Name.Substring(9) will remove AddButton and leave number) and change Label.Text to TextBox.Text.

    Get all label values and insert them in database:

    Private Sub save(sender As Object, e as EventArgs) Handles button_save_subjects.Click
    For i = 1 to number
        Dim value As String
        value = CType(Me.Controls.Find("Label"+number.ToString).First,Label).Text
        'insert into database
    Next
    End Sub
    

提交回复
热议问题