user7204131 user7204131 - 16 days ago 6
Vb.net Question

Controling dynamic textboxes

I want to make a program that adds 6

TextBox
controls by clicking a button and then show the sum of 6 number in text boxes in a label.

I have written code that adds text boxes but I have problem with their sum. How can I get all text boxes values?

Public Class Form1
Dim txtn As Integer = 1
Dim sum As Integer


Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
AddNewTextBox()
End Sub
Public Function AddNewTextBox() As TextBox
Dim txt As New TextBox()
Controls.Add(txt)
txt.Top = txtn * 25
txt.Left = 200
If txtn < 6 Then
txtn = txtn + 1
Return txt
Else
MsgBox("sorry you reached the max number of text boxes")
End If
End Function

Private Sub Label1_Click(sender As Object, e As EventArgs) Handles Label1.Click
Label1.Text = 'problem???
End Sub

End Class

Answer

You need to get a hold of a reference to the textboxes you are creating dynamically. You can do this by adding them to the list when you're creating them and then accessing them when you're summing up.

Public Class Form1
    Dim txtn As Integer = 1
    Dim sum As Integer

    Private _textboxesToSum As New List(Of TextBox)

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        AddNewTextBox()
    End Sub

    Public Function AddNewTextBox() As TextBox
        Dim txt As New TextBox()
        Controls.Add(txt)
        _textboxesToSum.Add(txt)
        txt.Top = txtn * 25
        txt.Left = 200
        If txtn < 6 Then
            txtn = txtn + 1
            Return txt
        Else
            MsgBox("sorry you reached the max number of text boxes")
        End If
    End Function

    Private Sub Label1_Click(sender As Object, e As EventArgs) Handles Label1.Click
        Label1.Text = _textboxesToSum.Select(Of Integer)(Function(t) If(IsNumeric(t.Text), t.Text(), 0)).Sum()
    End Sub

End Class

You can also do it by iterating through all textboxes on your form, but you might have some other textboxes there, serving some other purpose.