在不实例化的情况下处理表单 [英] Manipulate a form without instantiating it
问题描述
我正在VB.NET 2005中工作.假设我有一个具有两种形式的项目.第一种形式是启动对象.在第一个窗体上,有一个按钮,当单击该按钮时,它将从第二个窗体(Form2.Controls.Remove(Form2.Label1))中删除控件.单击第二个按钮,第二个窗体出现(Form2.Show),其中包含控件已删除.
我不知道是什么原因.第二种形式从不实例化.我期望得到对象变量未设置为实例..."
当然,这种编码非常糟糕,我也不打算使用任何类似的编码,但是我试图向同事证明一点,他认为她可以通过这种方式从第二种形式中删除控件.
第一个窗体上还有一个第三个按钮,用于刷新Form2.单击该按钮,然后单击显示"按钮,随即出现第二个窗体及其所有控件.
但是,为什么我可以在不实例化第二种形式的情况下完成所有这些操作呢?
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?
推荐答案
我不确定我认为这是因为与VB6兼容.在vb6中,您可以执行此操作.我记得,当我使用VB.net 2005(alpha或beta)版本或2003时,这是不可能的,后来-我认为出于兼容性-他们使之成为可能.
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.
老实说,这个问题使我很感兴趣,所以我进行了测试.
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
这篇关于在不实例化的情况下处理表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!