Mubby
Mubby

Reputation: 95

Defining Form into variable vb.net

If you want to insert a variable Form2, I use this ..

Dim Variable As New Form2

But if I have the same functions with names in two forms, I'll do it using if.

if 1 = 1 Then
     Dim Variable As New Form2
Else
     Dim Variable As New Form3
End If

That's perfectly fine, but if I start using this variable in the code below, an error occurs if I use without conditions, everything is fine, use when the condition seemed to understand what to do.

Variable.DataGridView1.Rows.Add(row)

Object reference not set to instance of an object

Upvotes: 1

Views: 1230

Answers (1)

Matt Wilko
Matt Wilko

Reputation: 27322

You need to declare your variable first and then assign it to a particular type:

Dim Variable As Form = Nothing
If 1 = 1 Then
   Variable = New Form2()
Else
   Variable = New Form3()
End If

But usually you would do this in an object oriented approach by each form implementing a common interface.

You can then do this:

Dim Variable As IForm
If 1 = 1 Then
   Variable = New Form2() 'Form2 implements IForm
Else
   Variable = New Form3() 'Form3 implements IForm
End If

Upvotes: 1

Related Questions