D Torres D Torres - 3 years ago 123
Vb.net Question

Instances of a form

I got a problem and I'm a little confused, so I'm just going to put it simple:

I have 2 forms (form1 and form2).

Form1 has a tabcontrol which shows form2 in a tabpage.
Form2 has a button1 that closed itself and therefore the tabpage.

I'm using this code for button1:

Dim f1 As New Form1()
f1.tabControl1.Controls.Remove(f1.tabControl1.Selectedtab)


Using the above code I got an exception so just to be sure that the tabpage is there i add this in button1 before removing the tabpage:

Console.Writeline(f1.tabControl1.TabCount)


Using the instance shows 0. But using the default instance shows 1:

Console.Writeline(Form1.tabControl1.TabCount)


I want to know if I'm doing something wrong creating an instance

Pd: I know I can use this:

Form1.tabControl1.Controls.Remove(Form1.tabControl1.Selectedtab)


But I need to work with instance

Edit:

I got a NullReferenceException when i use:

Dim f1 As New Form1()
f1.tabControl1.Controls.Remove(f1.tabControl1.Selectedtab)


As i said, it works if i use the deafult instance

Edit 2:

This is the code i use to create the tabpage, this method is in form1 and i call it in a click event of a button in form1:

Dim tabpage1 as new Tabpage
Dim f2 as new Form2

tabpage1.Controls.Add(f2)
f2.show()

tabControl1.TabPages.Add(tabpage1)

Answer Source

i got the answer: In form2:

Dim f1 As New Form1
Public Sub New(ByRef _f1)
' TODO: Complete member initialization 
InitializeComponent()
f1 = _f1
End Sub

I just had to reference form1

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