0

I have 3 check boxes that I want to act as a radial button group, but my new job is in vb.net and WinForms.

My hope was to simplify the 3 event handlers by replacing the commented code with a function call like this:

Private Sub cbLinqQuery_CheckedChanged(sender As Object, e As EventArgs) handles cbLinqQuery.CheckedChanged
    SafeCheckChg(cbDataTable, cbDataTable_CheckedChanged, cbLinqQuery.Checked)
    'RemoveHandler cbDataTable.CheckedChanged, AddressOf cbDataTable_CheckedChanged
    'cbDataTable.Checked = Not cbLinqQuery.Checked
    'AddHandler cbDataTable.CheckedChanged, AddressOf cbDataTable_CheckedChanged

    RemoveHandler cbArray.CheckedChanged, AddressOf cbArray_CheckedChanged
    cbArray.Checked = Not cbLinqQuery.Checked
    AddHandler cbArray.CheckedChanged, AddressOf cbArray_CheckedChanged

    btnDefaultBoundData_Click(sender, e)
End Sub

Private Sub SafeCheckChg(ByRef cb As CheckBox, ByRef handler As EventHandler, checked As Boolean)
    RemoveHandler cb.CheckedChanged, AddressOf handler
    cb.Checked = Not checked
    AddHandler cb.CheckedChanged, AddressOf handler.Clone
End Sub

But I've had no success passing the event handler as a parameter. I've tried passing it as an event handler, a delegate and a void but using it in the RemoveHandler/AddressOf call doesn't seem to be understood by the compiler.

Is there a method where I can get the event handler off of the passed object? Is there a type I can use as the parameter. Obviously I'm not desperate, this is in the name of better code not better functionality.

xpda
  • 15,585
  • 8
  • 51
  • 82
user314321
  • 390
  • 3
  • 24

1 Answers1

1

So Found a pretty close answer that worked with a small tweak:

Inspiration

Solution was simply to pass AddressOf foo as the parameter and remove the AddressOf from the RemoveHandler / AddHandler call. (Which for some reason I thought was a required part of the Add/RemoveHandler call and not a separate function call operating on a parameter.)

Final Code:

Private Sub cbLinqQuery_CheckedChanged(sender As Object, e As EventArgs) Handles cbLinqQuery.CheckedChanged
    SafeCheckChg(cbDataTable, AddressOf cbDataTable_CheckedChanged, cbLinqQuery.Checked)
    SafeCheckChg(cbArray, AddressOf cbArray_CheckedChanged, cbLinqQuery.Checked)
    btnDefaultBoundData_Click(sender, e)
End Sub

Private Sub SafeCheckChg(ByRef cb As CheckBox, ByRef handler As EventHandler, checked As Boolean)
    RemoveHandler cb.CheckedChanged, handler
    cb.Checked = checked
    AddHandler cb.CheckedChanged, AddressOf handler.Clone
End Sub
Community
  • 1
  • 1
user314321
  • 390
  • 3
  • 24