First of all, your code is not optimized. And i can only ask you one question: How many
for - next
loops you want to use, if every time you iterate through the collection of
LisBox1.Items
?
Second, use
With - End With
block to set many properties for one control.
Third, use simple trick:
Public Class Form1
WithEvents oBtnAdd As Button
WithEvents oBtnSubst As Button
Private Sub CreateDynamicControls()
Dim but As Button = Nothing
Dim txt As TextBox = Nothing
Dim i As Integer
For i = 1 To 10
but = New Button
With but
.Location = New Point(500, 150 + (i * 25))
.Tag = i.ToString
.Name = "ButtonSubst" & i
.Width = 24
.Text = "-"
.Parent = Me
AddHandler but.Click, AddressOf oBtnSubst_Click
End With
txt = New TextBox
With txt
.Location = New Point(525, 150 + (i * 25))
.Name = "TextBox" & i
.Tag = i.ToString
.Width = 45
.Text = 0
.Enabled = False
.Parent = Me
End With
but = New Button
With but
.Location = New Point(571, 150 + (i * 25))
.Tag = i.ToString
.Name = "ButtonAdd" & i
.Width = 24
.Text = "+"
.Parent = Me
AddHandler but.Click, AddressOf oBtnAdd_Click
End With
Next i
End Sub
Public Sub oBtnAdd_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles oBtnAdd.Click
Dim btn As Button = sender
Dim txt As TextBox = CType(Me.Controls("TextBox" & btn.Tag), TextBox)
Dim count As Integer = Integer.Parse(txt.Text)
txt.Text = count + 1
End Sub
Public Sub oBtnSubst_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles oBtnSubst.Click
Dim btn As Button = sender
Dim txt As TextBox = CType(Me.Controls("TextBox" & btn.Tag), TextBox)
Dim count As Integer = Integer.Parse(txt.Text)
txt.Text = count - 1
End Sub
Public Sub New()
InitializeComponent()
CreateDynamicControls()
End Sub
End Class