你好这是我的代码
Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
TextBox1.Text = Val(TextBox1.Text)
End Sub
Private Sub TextBox2_TextChanged(sender As Object, e As EventArgs) Handles TextBox2.TextChanged
TextBox2.Text = Val(TextBox2.Text)
End Sub
Private Sub TextBox3_TextChanged(sender As Object, e As EventArgs) Handles TextBox3.TextChanged
TextBox3.Text = Val(TextBox3.Text)
End Sub
Private Sub TextBox4_TextChanged(sender As Object, e As EventArgs) Handles TextBox4.TextChanged
TextBox4.Text = Val(TextBox4.Text)
End Sub
Private Sub TextBox5_TextChanged(sender As Object, e As EventArgs) Handles TextBox5.TextChanged
TextBox5.Text = Val(TextBox5.Text)
End Sub
Private Sub TextBox6_TextChanged(sender As Object, e As EventArgs) Handles TextBox6.TextChanged
TextBox6.Text = Val(TextBox6.Text)
End Sub
如何为所有文本框制作短代码? 我尝试使用这段代码我没有工作
Dim i As integr
TextBox(i).text = Val(TextBox(i).text)
感谢您的帮助
答案 0 :(得分:2)
为所有人使用一个处理程序:
Private Sub TextBox_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged, _
TextBox2.TextChanged, _
TextBox3.TextChanged, _
TextBox4.TextChanged, _
TextBox5.TextChanged, _
TextBox6.TextChanged
Dim txt = DirectCast(sender, TextBox)
txt.Text = Val(txt.Text)
End Sub
答案 1 :(得分:1)
您只需要创建一个TextChanged处理程序,然后将所有Texbox事件绑定到它。
Private Sub TextBox_TextChanged(sender As Object, e As EventArgs) _
Handles TextBox1.TextChanged, TextBox2.TextChanged, <...for all your textboxes ..>
Dim target = DirectCast(sender, TextBox)
target.Text = Val(target.Text)
End Sub
如果要绑定代码中的所有文本框,可以在加载表单后以编程方式执行此操作:
Dim allTextBoxes = Me.Controls.OfType(Of TextBox)()
For Each textbox In allTextBoxes =
AddHandler textbox.TextChanged, AddressOf TextBox_TextChanged
Next
答案 2 :(得分:0)
除了Murray Foxcroft的回答。您可以动态创建文本框的处理程序,并通过执行
将其代码的子例程添加到其中Dim textboxes = Me.Controls.OfType(Of TextBox)()
For Each txt in textboxes
AddHandler textbox.TextChanged, Sub(sender As Object, e As EventArgs)
... (using sender to find out which textbox sent the command)
End Sub
Next