将值从一个窗体控件转移到另一个窗体控件时,将导致null引用异常 [英] null reference exception while transfering value from one form control to another form control

查看:107
本文介绍了将值从一个窗体控件转移到另一个窗体控件时,将导致null引用异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,

将值从一个窗体控件转移到另一个窗体控件时,获取空引用异常.

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.

推荐答案

在问这样的问题时,应始终指出抛出异常的行.总是.在询问此类问题之前,请始终在调试器下运行它.请勿排除.

让我们来看看. label1textBox1为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 that label1 or textBox1 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.

But this.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, then f becomes null and the first attempt to de-reference it by getting f.textBox1 throws that exception.

Want to check it up? Finally, run it under debugger. Always, always do it.

—SA


这篇关于将值从一个窗体控件转移到另一个窗体控件时,将导致null引用异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆