将值从一个窗体控件转移到另一个窗体控件时,将导致null引用异常 [英] null reference exception while transfering value from one form control to another form control
问题描述
大家好,
将值从一个窗体控件转移到另一个窗体控件时,获取空引用异常.
private void button1_Click(对象发送者,EventArgs e)
{
Form1 f =(Form1)this.Owner;
如果(label1.Text =="1")
{
f.textBox1.Text = textBox1.Text;
}
this.Close();
}
请帮忙.
Hi All,
Getting a null reference exception while transfering value from one form control to another form control.
private void button1_Click(object sender, EventArgs e)
{
Form1 f=(Form1)this.Owner;
if (label1.Text == "1")
{
f.textBox1.Text = textBox1.Text;
}
this.Close();
}
Please help.
推荐答案
在问这样的问题时,应始终指出抛出异常的行.总是.在询问此类问题之前,请始终在调试器下运行它.请勿排除.
让我们来看看.label1
或textBox1
为null的可能性很小.不太可能.它们的丑陋名称(从不使用自动生成的名称;它们违反(良好的)Microsoft命名约定;始终保持某种语义;为什么您认为它们为您提供了重构引擎?)表明它们是自动生成的,几乎不会为空. br/>
但是this.Owner
很可能可以为null.所有权是非常有用的关系.如果使用多个表单,请始终使所有表单归主表单所有.但是-您做到了吗?不?好吧,然后f
变为null,并且第一次尝试通过获取f.textBox1
取消引用它会抛出该异常.
想检查一下吗?最后,在调试器下运行它.永远,永远做.
—SA
You should always indicate the line where exception is thrown when asking questions like that. Always. Always run it under debugger before asking such questions. Make no exclusions.
Let''s see. It'' very unlikely thatlabel1
ortextBox1
is null. Very unlikely. Their ugly names (never ever use auto-generated names; they violate (good) Microsoft naming conventions; always remain to something semantic; why do you think they gave you refactorization engine?) suggest that they are auto-generated and hardly null.
Butthis.Owner
is very likely can be null. Ownership is a very useful relationship. If you use more than one form, always make all forms owned by the main form. But — did you do it? No? Well, thenf
becomes null and the first attempt to de-reference it by gettingf.textBox1
throws that exception.
Want to check it up? Finally, run it under debugger. Always, always do it.
—SA
这篇关于将值从一个窗体控件转移到另一个窗体控件时,将导致null引用异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!