0

I have a control on a form UserNameCtrl and that control has a sub called LoadCtrl

I essentially have loads of these subs for clicks, so I want to put them all into one event handler

Private Sub NewsletterBtn_Click(sender As Object, e As EventArgs) Handles NewsletterBtn.Click, NewsletterImage.Click
    If Not MainNewsletterCtrl.Loaded() Then MainNewsletterCtrl.Load()
End Sub

However within each of the subs the control names are hardcoded to call the .loaded and .load functionality.

I've wrote a new version of this

Private Sub GenericNavItem_Click(sender As Object, e As EventArgs)
        Dim ctrl As Control = Controls.Find(sender.tag, True).FirstOrDefault

       'Want to do the Controlname.Load here           

    End Sub

Using the tag (which I named as the control name) I got the corresponding control. But it's bringing back it as a control rather than of the type I want it to be.

I know I declare it as Control, but I don't know how I can cast it to be the ControlName.Load rather than the generic control.

1
  • Do these controls inherit from a base control or implement an interface that has the Loaded() and Load() methods? Commented Jun 22, 2017 at 11:42

1 Answer 1

1

If they are all the same class (or base class), then just cast to that class. If they are all different class but have the same method Load and Loaded, then I suggest you create an interface.

Interface ISomeName

    Sub Load()
    Function Loaded() As Boolean()

End Interface

Make sure all your class implement it and then just cast to that interface.

Private Sub GenericNavItem_Click(sender As Object, e As EventArgs)
    Dim ctrl As Control = Controls.Find(sender.tag, True).FirstOrDefault
    Dim ctrlInterface As ISomeName = CType(ctrl, ISomeName)

    If Not ctrlInterface.Loaded() Then ctrlInterface.Load()

End Sub
Sign up to request clarification or add additional context in comments.

1 Comment

Yes, this is fantastic. I don't know why I didn't think of this before. Thank you, my code is much cleaner now. @the_lotus

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.