控制动态文本框



我想制作一个程序,通过单击按钮添加 6 个TextBox控件,然后在标签的文本框中显示 6 个数字的总和。

我编写了添加文本框的代码,但我对它们的总和有问题。如何获取所有文本框值?

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

您需要获取对正在动态创建的文本框的引用。为此,您可以在创建它们时将它们添加到列表中,然后在汇总时访问它们。

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

您也可以通过循环访问窗体上的所有文本框来执行此操作,但您可能还有其他一些文本框,用于其他目的。

在此之前,请确保验证输入Texbox仅为数字

Private Sub Label1_Click(sender As Object, e As EventArgs) Handles Label1.Click
Dim i As Integer = 0
For Each T As Textbox In Me.Controls.OfType(Of TextBox)()
Try
i = i + Val(t.text)
Catch ex As Exception
End Try
Next
Label1.Text = i
End Sub

循环已更新...

最新更新