Click here to Skip to main content
15,848,904 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I'm working in VB.NET 2005. Assume I have a project with two forms. The first form is the startup object. On the first form, there is a button that, when clicked, removes controls from the second form (Form2.Controls.Remove(Form2.Label1). Click a second button and the second form appears (Form2.Show), with the controls removed.

What I can't figure out is why this works. The second form is never instantiated. I expected to get "Object variable not set to an instance..."

Of course this sort of coding is terrible, and I don't plan to ever use anything like it, but I am trying to prove a point to a co-worker who thinks she can remove controls from the second form this way.

There's also a third button on the first form, that refreshes Form2. Click that and then click the Show button, and the second form appears with all of its controls.

But why can I do all of this without instantiating the second form?
Posted

Hi,

I am not sure bu I think it is because of the compatibility to VB6. In vb6 you could do this. As I remember, when I worked with VB.net 2005 (alpha or beta ) version or maybe 2003, it was not possible and later -I think for compatibility- they made it possible.
 
Share this answer
 
v2
In all honesty this question intreged me, so I tested it.

Public Class Form1
    Private frm As Form2

    Private Sub Button1_Click(ByVal sender As System.Object, 
      ByVal e As    System.EventArgs) Handles Button1.Click  
       
       frm.Controls.Remove(frm.Button1)

    End Sub

    Private Sub Button2_Click(ByVal sender As System.Object, 
      ByVal e As System.EventArgs) Handles Button2.Click
     
        frm.Show()

    End Sub
End Class


That gives a null reference exception, so the only way to do this is to create the

dim frm as form2


as

dim frm as new form2


thus allowing the action to be performed. So to answer your question the form has to be instantiated for the action to be completed.

And yes I agree that this isn't the best way to do such actions. I would prefer to pass a flag of some description and remove the control on the new or loading methods depending on the overall logic of the form manipluation
 
Share this answer
 
Comments
aidin Tajadod 12-Oct-10 14:30pm    
you need to call Form2.controls.remove instead of frm.controls.remove !
Simon_Whale 13-Oct-10 6:43am    
That does work but I have never seen code done in that way.. through examples or in books to be honest
aidin Tajadod 13-Oct-10 17:33pm    
ya, you are right, because it is not the right way to do that. But in VB6 I have seen too many codes like that!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900