# VB.Net Accessing Parent Form



## Darkicon (Feb 12, 2008)

I'm having a problem accessing a form from another form. I declared the other form, but for some reason I just get a NullReferenceException. Here's the code:


```
[COLOR="Blue"]Public Class[/COLOR] loginwin
    [COLOR="Blue"]Dim[/COLOR] f [COLOR="Blue"]As[/COLOR] Form1

    [COLOR="Blue"]Private Sub[/COLOR] Button1_Click([COLOR="Blue"]ByVal[/COLOR] sender [COLOR="Blue"]As[/COLOR] System.Object, [COLOR="Blue"]ByVal[/COLOR] e [COLOR="Blue"]As[/COLOR] System.EventArgs) [COLOR="Blue"]Handles[/COLOR] Button1.Click
        Try
            [COLOR="Blue"]If[/COLOR] usrn.Text.Length >= 1 [COLOR="Blue"]And[/COLOR] psw.Text.Length >= 1 [COLOR="Blue"]Then[/COLOR]
                f.address.Text = [COLOR="Sienna"]"000"[/COLOR] [COLOR="SeaGreen"]'address textbox is in Form1.[/COLOR]
            [COLOR="Blue"]End If[/COLOR]
            [COLOR="Blue"]Catch[/COLOR] ex [COLOR="Blue"]As[/COLOR] Exception
            MsgBox([COLOR="Sienna"]"An unknown error has occurred."[/COLOR], MsgBoxStyle.SystemModal, [COLOR="Sienna"]"Error"[/COLOR])
        [COLOR="Blue"]End Try[/COLOR]
    [COLOR="Blue"]End Sub[/COLOR]
[COLOR="Blue"]End Class[/COLOR]
```


----------



## Ent (Apr 11, 2009)

It would be nice to have a little more information about what you already have. You have a base form loginwin, and a button Button1 on loginwin? Have you also created form1 in the design view?

That is the crucial question. You don't need to dimension a form which you've created in the design view. When you just want to open such a pre-created form, use form1.show() to bring it up, and then you can fiddle public properties all you want. For example the line would be

```
form1.address.text = "000"
```
 This MUST come after the show command, or you get your error code.

You should rename form1 f to be consistent with your plan. In theory there is an alternative: you could also say

```
dim f as form1
```
 as you have done. However that still needs the show command and would normally be a bad idea unless there's a really good reason for it, because it takes up unnecessary memory (assigns space for f AND form1) and more time. It also makes it almost inevitable that you'll get bugs for calling (accidentally) f one time but form1 the next time, such that neither works as planned.

Interestingly you can actually use Dim with forms (dim f as new form with {attributes}) to create a simple form without going through the design view at all. I've done that a few times to make my own simple pop-up messages. You still need to use show to bring them up and close to make them go away again.

Hope that's what you needed.
Ent


----------



## pvc_ (Feb 18, 2008)

you have not instantiated the f form. Use the keyword "new" to instantiate the form and use the ".show" property to create the form.

dim f as new form1
f.show();

also make sure the textbox on the form is public or else you wont be able to access it.


----------

