我想创建一个程序,通过单击按钮添加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
答案 0 :(得分:0)
在此之前,请确保验证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
循环更新......
答案 1 :(得分:0)
您需要获得对动态创建的文本框的引用。你可以在创建它们时将它们添加到列表中,然后在总结时访问它们。
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
您也可以通过遍历表单上的所有文本框来执行此操作,但您可能还有其他一些文本框,用于其他目的。