vb.net InitializeComponent() is not declared

19.6k views Asked by At

I want to use InitializeComponent() when I create a custom control (to be sure everthing is initialized before I use it), but the compiler says it's not declared. But my Designer.vb contains a sub:

<System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()

with all new instances I created.

Why can't I call that?

edit this is how I call InitizialeComponent:

Public Class CustomControlsTextBox : Inherits TextBox
Public Sub New()
    MyBase.New()
    InitizialeComponent() 'this function is not declared
End Sub
End Class
2

There are 2 answers

0
Alex On

You should not depend on your Designer.vb's InitializeComponent. Rather, create a new constructor in your Form1 which will call InitializeComponent()

For example:

Public Class Form1

    Public Sub New()
        ' This call is required by the designer.
        InitializeComponent()

        ' Add any initialization after the InitializeComponent() call.
        'Type all your code here! This code will be executed before the "FormLoad" if you call your new form
    End Sub
End Class

Now whenever we use the following code:

Dim NewFrm1 As New Form1

The New constructor in Form1 will be called.

4
MACN On

InitializeComponent() is private, and can only be called from inside that class. It is called by default by the usercontrol constructor, like this:

Public Sub New()

    ' This call is required by the designer.
    InitializeComponent()

    ' Add any initialization after the InitializeComponent() call.

End Sub

Note that you will only have to call InitializeComponent() yourself if you overload the constructor. Default constructor does it by itself.