I am making a windows form application. I want to detect which checkbox is being selected by the user. One way to check this would be to loop through all the controls everytime a checkbox checkchanged event is fired. But I do not want to do that because multiple checkboxes could be checked. I want to get the ID of checkbox as it is selected or on a mousedown event. How can I do so?

有帮助吗?

解决方案

You can add the event handlers for the checkboxes you want at runtime. Use the Where clause to filter by name if applicable. This code does it in form_load.

Inside the handler, you can cast sender to a local variable which represents the checkbox which was checked, if you want.

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    For Each checkBox In Me.Controls.OfType(Of CheckBox)().Where(Function(cb As CheckBox) cb.Name.Contains("CheckBox"))
        AddHandler checkBox.CheckedChanged, AddressOf checkboxCheckedChanged
    Next
End Sub

Private Sub checkboxCheckedChanged(sender As Object, e As EventArgs)
    Dim myCheckbox As CheckBox = DirectCast(sender, CheckBox)
    Dim c As Boolean = myCheckbox.Checked
    Dim n As String = myCheckbox.Name
    ' etc.
End Sub

EDIT

As Neolisk pointed out, this doesn't account for nested controls, i.e. controls inside containers on the form. This extension method returns all those controls:

<Extension()> _
Public Function ChildControls(Of T As Control)(ByVal parent As Control) As List(Of T)
    Dim result As New List(Of Control)
    For Each ctrl As Control In parent.Controls
        If TypeOf ctrl Is T Then result.Add(ctrl)
        result.AddRange(ctrl.ChildControls(Of T)())
    Next
    Return result.ToArray().Select(Of T)(Function(arg1) CType(arg1, T)).ToList()
End Function

And make this the loop in form_load instead:

    For Each checkBox In Me.ChildControls(Of CheckBox).Where(Function(cb As CheckBox) cb.Name.Contains("CheckBox"))
        AddHandler checkBox.CheckedChanged, AddressOf checkboxCheckedChanged
    Next

其他提示

Use sender argument in the event handler.

Private Sub CheckBox1_CheckedChanged(sender As Object, e As EventArgs) _
                                                 Handles CheckBox1.CheckedChanged
  'DirectCast(sender, CheckBox).Name ?
End Sub
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top