Rewriting Code.

Jay1b

Member
Joined
Dec 12, 2007
Messages
21
Programming Experience
5-10
Guys

I was hoping someone could please help me. I have a piece of code which works fine, but looks incredibly messy and ideally i'd like to make it easier to reuse.

VB.NET:
        For Each np As Control In NavBar1.Controls
            If TypeOf np Is NavBarPanel Then
                If np.Name = "NavPanelCalendar" Then
                    Dim nsb As NavBarSubButton = np.Controls("subBtnUpcoming")
                    AddHandler nsb.Click, AddressOf frmUpcoming
                End If
            End If
        Next

NavBar1 is a usercontrol, which has a collection of NavBarPanels on it, these are custom controls inheriting from the Panel control. The NavBarPanels have a number of NavBarSubButton's on it, which are also custom controls inheriting from the button control.

I have tried both of the following, but they both come up with 'Object reference not set to an instace of a object'.

VB.NET:
        'Attempt 1
        Dim nsb2 As NavBarSubButton = NavBar1.Controls("NavPanelCalender").Controls("subBtnUpcoming")
        AddHandler nsb2.Click, AddressOf frmUpcoming

        'Attempt 2
        AddHandler (NavBar1.Controls("NavPanelCalender").Controls("subBtnUpcoming")).Click, AddressOf frmUpcoming

As their are several NavBarPanels, the method i have working looks a little untidy and unwieldy!


Also is there a simple way of using delegates via strings? For example:
VB.NET:
AddHandler nsb2.Click, AddressOf frmUpcoming
I would just like to pass the delegate method name into it via code. The delegate name being stored into a database, ideally I would like to store the entire method in a database, but i'm guessing this would be much more complex!



Thanks for any help you may be able to give.
 
I dont really understand what youre talking about but if you want to map strings to objects, you need a dictionary:

Dim dic as Dictionary(Of String, MyWhateverDelegate)

dic("nav1Handler") = New MyWhateverDelegate(nav1HandlerFunction)


Or however it would be written in VB.. this is more like C# (i'm a c# guy, sorry) - thing is that delegates are objects tied to methods but you will need to ahve a comprehensive list of every delegate, the method it ties to, and a string to refer to that delegate.. addhandler should be anle to work with that..

in c# i'd say something like:

VB.NET:
foreach BaseControl c in myNavBar.Controls
  c.CommonEvent += dic(c.Name)

to attach a relevant delegate to a named control..
 
The way you've done in Attempt1/2 works, you must have the names wrong.

AddressOf is short for creating the correct delegate for the event and pointing it to the method, this can be done with reflection:
VB.NET:
AddHandler nsb2.Click, System.Delegate.CreateDelegate(GetType(EventHandler), Me, "frmUpcoming")
 
Back
Top