Simonetos Simonetos - 2 years ago 322 Question

Visual Basic.NET - Windows form actions like close through custom user control code?

I have made a title bar (custom user control) that contains five controls. They are all labels but each one do different "job".

For example, one of them is an exit form button. If I put a

event into my custom user control's code, for example...

Private Sub ExitButton_Click(sender As Object, e As EventArgs) Handles ExitButton.Click
End Sub

I get this error...

BC30451 'Close' is not declared. It may be inaccessible due to its protection level.

On the other hand I can't put it into my project's code cause it can't find
as "isolated" control and do

Any suggestions? I also want to do the same thing with minimize, maximize etc.

Answer Source

Let me guess; your button is in the user control. You try to call Close() on the UserControl class, which obviously is not a window and does not have it.

There are three solutions:

  • Use the ParentForm property and call Close() on it (e.g. ParentForm.Close()). Easy but not too flexible; if you want to do other things than those which are implemented in the Form base class (like Close()), e.g. specific to the main form, you would have to cast it first and check if it's really the form you thought of. Also, all those things would need to be exposed with Public or Internal, don't expose what you don't have to expose.
  • You pass the Form to the UserControl. Horrible because passing stuff around just ends up in spaghetti code.
  • Better, raise an event by the UserControl which you handle in the form the UserControl is on. That's probably the most flexible approach.

Here's a small code example solving this with an event:

Open the code of the UserControl and add an event signature and raise that event when you click the button:

Public Class MyUserControl

    Public Event ButtonClicked(sender As Object, e As EventArgs)

    Private Sub MyButton_Click(sender As Object, e As EventArgs) Handles MyButton.Click
        RaiseEvent ButtonClicked(sender, e)
    End Sub

End Class

Then, in your Form, attach to the ButtonClicked event of the UserControl:

Public Class MyForm

    Private Sub MyUserControl1_ButtonClicked(sender As Object, e As EventArgs) Handles MyUserControl1.ButtonClicked
    End Sub

End Class

If you re-use the event for multiple buttons, you can check which button it is through the sender passed to the event. (Of course this can be optimized by just passing a casted Button instance as the event parameter, this is just a simple example).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download