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

后端 未结 5 1521
滥情空心
滥情空心 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:45

    A control like a textbox is just an object of the class Textbox. In order for the form to display this object it needs to be added to the form's Controls property. To create a new textbox all you need to do is

    Dim newTB as New Textbox
    newTB.Name = "tbNew"
    'Set location, size and so on if you like
    Me.Controls.Add(newTB)
    

    If you want your control to be able to respond to events you need to add an event handler for the event you want to the control. This handler refers the event to a method of your choice.

    Public Class Form1
    
      Sub CreateTB
        Dim NewTB as New Textbox
        newTB = New Textbox
        newTB.Name = "tbNew"
        AddHandler newTB.TextChanged, AddressOf HandleTextChanged
        Me.Controls.Add(newTB)
      End Sub
    
    
      Private Sub HandleTextChanged(sender as Object, e as EventArgs)
        'Handle the event
      End Sub
    End Class
    

    You should make sure that the names are unique if you are creating the controls or you might run into trouble.

    You can also store your created controls in an array or list as a global variable. That way you can easily access them afterwards.

提交回复
热议问题