-
Using a delegate
Hi all,
Suppose we got a form with some checkboxes.
Each ckeckbox represents a method of the same class.
Each method takes no arguments, returns no values.
Is it possible using a delegate to loop through the checkboxes and run only the methods being checked?
Thanks
-
Re: Using a delegate
It might be easier to use reflection and interfaces.
-
Re: Using a delegate
possible? sure, I suppose... I mean it's possible I could win the lottery this weekend...
The question that you should be asking is, what purpose would that serve? I'm not sure I get how a delegate would work in this case... reflection, that I get... maybe... but it depends on what you're trying to accomplish.
-tg
-
Re: Using a delegate
You could associate an Action with each CheckBox, and Invoke the Actions associated with the checked checkboxes. How you do this association is up to you, you could have a Dictionary(Of CheckBox, Action), you could use the Tag property, etc.
Example:
Code:
Private checkboxes As Dictionary(Of CheckBox, Action)
Private Sub SetupCheckboxes()
checkboxes = New Dictionary(Of CheckBox, Action)()
checkboxes.Add(CheckBox1, New Action(AddressOf Method1))
checkboxes.Add(CheckBox2, New Action(AddressOf Method2))
checkboxes.Add(CheckBox3, New Action(AddressOf Method3))
checkboxes.Add(CheckBox4, New Action(AddressOf Method4))
End Sub
Private Sub ExecuteMethods() 'Call on button click or whatever
For Each kvp As KeyValuePair(Of CheckBox, Action) In checkboxes
Dim checkbox = kvp.Key
Dim action = kvp.Value
If checkbox.Checked Then action.Invoke()
Next
End Sub
(Not very sure about syntax, it's been a while since I fired up VB)
That's how you could do it, whether it's useful? I dunno... There are probably better ways to do what you want.
-
Re: Using a delegate
Thanks Nick, first i will try reflection.
Thank you