使用对象时的例外情况 [英] Exception in using object

查看:115
本文介绍了使用对象时的例外情况的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我使用类的对象时,它会给出异常对象引用未设置为对象的实例

我的代码是

When I use object of class it gives exception "Object reference not set to an instance of an object"
my code is

Customer cms=null;
 protected void Page_Load(object sender, EventArgs e)
        {
           
            if (!IsPostBack)
            {
                cms= new Customer();              
              
            }

        }
protected void btnsubmit_Click(object sender, EventArgs e)
        {
cms.GetCode(); //exception is here
}

推荐答案

这是因为你正在检查!IsPostBack。请记住,这是在服务器上执行的代码。因此,当单击按钮时,您的Page_Load首先运行,但是从那时起!IsPostBack存在cms = null,因为它在类中以这种方式定义。然后btn提交点击火。



只需在btnsubmit中启动cms = new Customer()。
It is because you are checking for !IsPostBack. Remember, this is code that executes on the server. So, when the button is clicked your Page_Load first runs but since !IsPostBack is there cms = null because it is defined that way in the class. Then btnSubmit click fires.

Just start cms= new Customer() in btnsubmit.


如果 IsPostBack 不是 false ,然后 cmd reamins null 因此你得到了例外。
if IsPostBack is not false, then cmd reamins null, hence you get the exception.


这篇关于使用对象时的例外情况的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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