gpt4 book ai didi

vb.net - 在一个处理程序中处理所有文本框事件

转载 作者:行者123 更新时间:2023-12-01 22:58:22 25 4
gpt4 key购买 nike

我知道如何处理表单中的文本框事件。但想让这段代码更短,因为我将有 30 个文本框。使用它是低效的:

Private Sub TextBox1_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged, TextBox2.TextChanged, TextBox3.TextChanged, TextBox4.TextChanged, TextBox5.TextChanged, TextBox6.TextChanged, TextBox7.TextChanged, TextBox8.TextChanged, TextBox9.TextChanged, TextBox10.TextChanged
Dim tb As TextBox = CType(sender, TextBox)

Select Case tb.Name
Case "TextBox1"
MsgBox(tb.Text)
Case "TextBox2"
MsgBox(tb.Text)
End Select
End Sub

有没有办法缩短处理程序?

最佳答案

您可以使用 Controls.OfType + AddHandler 以编程方式。例如:

Dim textBoxes = Me.Controls.OfType(Of TextBox)()
For Each txt In textBoxes
AddHandler txt.TextChanged, AddressOf txtTextChanged
Next

一个处理程序:
Private Sub txtTextChanged(sender As Object, e As EventArgs)
Dim txt = DirectCast(sender, TextBox)
Select Case txt.Name
Case "TextBox1"
MsgBox(txt.Text)
Case "TextBox2"
MsgBox(txt.Text)
End Select
End Sub

关于vb.net - 在一个处理程序中处理所有文本框事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15358338/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com