您可能已经注意到,您可能需要在几个不同的地方执行此操作。要重用某个功能,请创建一个完成该工作的新方法。双击表单,并将其放在 End Class 之前:
''' <summary>Update each of the CheckBoxes that in the same GroupBox</summary>
''' <param name="sender">The CheckBox that was clicked.</param>
''' <param name="e"></param>
''' <remarks>It is assumed that only checkboxed that live in a GroupBox will use this method.</remarks>
Public Sub UpdateCheckBoxState(ByVal sender As System.Object, ByVal e As System.EventArgs)
'Get the group box that the clicked checkbox lives in
Dim parentGroupBox As System.Windows.Forms.GroupBox = DirectCast(DirectCast(sender, System.Windows.Forms.CheckBox).Parent, System.Windows.Forms.GroupBox)
For Each ctrl As System.Windows.Forms.Control In parentGroupBox.Controls
'Only process the checkboxes (in case there's other stuff in the GroupBox as well)
If TypeOf ctrl Is System.Windows.Forms.CheckBox Then
'This control is a checkbox. Let's remember that to make it easier.
Dim chkBox As System.Windows.Forms.CheckBox = DirectCast(ctrl, System.Windows.Forms.CheckBox)
If chkBox.CheckState = 1 Then
chkBox.Text = "Deselect All"
Else
chkBox.Text = "Select All"
End If
End If ' - is CheckBox
Next ctrl
End Sub
现在您有了一个可以做您想做的事情的方法,您需要将它连接到您要管理的每个 CheckBox。通过在 Form_Load 事件中添加以下代码来执行此操作:
AddHandler CheckBox1.CheckedChanged, AddressOf UpdateCheckBoxState
AddHandler CheckBox2.CheckedChanged, AddressOf UpdateCheckBoxState
...
因此,现在相同的方法将处理所有已连接复选框的 ClickChanged 方法。
除了用户单击它时,您还可以通过调用可能在 Form_Load 或其他地方的方法UpdateCheckBoxState(
CheckBoxThatYouWantToProgramaticallyUpdate来更新复选框。, Nothing)