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
Private Sub ExitButton_Click(sender As Object, e As EventArgs) Handles ExitButton.Click
BC30451 'Close' is not declared. It may be inaccessible due to its protection level.
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:
ParentFormproperty 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
Formbase 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
Internal, don't expose what you don't have to expose.
UserControl. Horrible because passing stuff around just ends up in spaghetti code.
UserControlwhich you handle in the form the
UserControlis 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
Public Class MyForm Private Sub MyUserControl1_ButtonClicked(sender As Object, e As EventArgs) Handles MyUserControl1.ButtonClicked Close() 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).