我有一个包含许多不同单选按钮,复选框和文本框的表单。根据他们的价值观,我开始计算。结果显示在相同的表格和面板上。如果我的任何控件(复选框,...)发生变化,我希望立即更新结果,而无需按任何更新按钮。 我可以为表单上的每个控件定义一个statsChanged-sub,但是有很多。当控件改变时,是否有一个表单的方式/事件开始?它应该像controlOnFormChanged。如果窗体上的任何控件发生更改,我怎样才能获得一个sub? 提前谢谢!
答案 0 :(得分:2)
您可以手动将与所需更改对应的事件连接到特定事件处理程序:
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'Iterate through all controls and handle them according to their type
For Each c As Control In Me.Controls
If TypeOf (c) Is CheckBox Then
AddHandler CType(c, CheckBox).CheckedChanged, AddressOf SomethingChanged
ElseIf TypeOf (c) Is RadioButton Then
AddHandler CType(c, RadioButton).CheckedChanged, AddressOf SomethingChanged
ElseIf TypeOf (c) Is TextBox Then
AddHandler CType(c, TextBox).TextChanged, AddressOf SomethingChanged
ElseIf ......
......
End If
Next
End Sub
Private Sub SomethingChanged(sender As Object, e As EventArgs)
'Whatever it is you do
End Sub
End Class
每当控件上的某个事件触发,就会调用子SomethingChanged,允许您更新结果。
请注意:如果您在Panels
等子容器中拥有控件,则需要修改此方法并迭代获取所有容器中的所有控件。
例如,这是一个解决方案:
http://kon-phum.com/tutors/pascal/programming_cs_getcontrolsonform.html
Public Shared Function GetAllControls(ctrls As IList) As List(Of Control)
Dim RetCtrls As New List(Of Control)()
For Each ctl As Control In ctrls
RetCtrls.Add(ctl)
Dim SubCtrls As List(Of Control) = GetAllControls(ctl.Controls)
RetCtrls.AddRange(SubCtrls)
Next
Return RetCtrls
End Function