Maury Markowitz Maury Markowitz - 2 years ago 59 Question

Implement a right-click for an entire group of check boxes?

I have a series of

(es) in a
that select what reports a user would like to run. They are normally all
, the most common case, but it is is also common to want to run just one. I thought using a right-click on a box to turn it on and all the others off would be useful.

It's easy enough to implement a
event on the check boxes, but the problem is that there are a bunch of them, and the list keeps getting added to. So the first question: is there a way to have a single
handler that works for any check box, even ones we don't have yet?

The other option would seem to be to use the
collection to loop over the check boxes and see which one was clicked and then set the
for all of them as appropriate. However, it seems that the
always intercepts the
event, even with
turned off. So my second question: is there a way to turn off click handling in the check boxes so that event can be handled by the group?

If there is any other way to handle this, please let me know!

Answer Source

Here's an example of what I'm talking about in my comments. Add a FlowLayoutPanel to a form (leaving it flowlayoutpanel1)

'This is done to show automatic generation of a list of reports.
'You might get this from a folder of reports, or a database or similar store
'By adding and taking away from this list you will notice that the code still functions the same.
'Just remember, you would dynamically fill the reports list in your real-world application.
Dim Reports As New List(Of String) From {"Report1", "Report2", "Report3", "Report4", "Report5", "Report6", "Report7", "Report8"}

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    'I'm using a flowlayoutpanel so that the controls are added
    'without having to worry about placement
    FlowLayoutPanel1.AutoScroll = True
    'Here is where we loop through the list of reports and add them to the 
    'flowlayoutpanel and give them a common handler
    For Each rpt As String In Reports
        Dim chkRpt As New CheckBox
        chkRpt.Text = rpt
        chkRpt.Height = 17
        chkRpt.Checked = True
        AddHandler chkRpt.MouseDown, AddressOf CustomMouseDown
End Sub

'Here is the code to allow a right click to select the current checkbox
'and remove all other checked items.
Private Sub CustomMouseDown(sender As Object, e As MouseEventArgs)
    If e.Button = Windows.Forms.MouseButtons.Right Then
        Dim curChk As CheckBox = CType(sender, CheckBox)
        For Each chk As CheckBox In FlowLayoutPanel1.Controls.OfType(Of CheckBox)()
            chk.Checked = False
        curChk.Checked = True
    End If
End Sub
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download