错误:对象引用未设置为对象的实例 [英] Error: Object reference not set to an instance of an object

查看:81
本文介绍了错误:对象引用未设置为对象的实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用asp.net gridview,我已经编写了用于插入,更新,删除和取消事件的代码.除更新事件外,所有事件代码均正常运行.调试我的应用程序时,它显示类似对象引用未设置为对象实例的错误.


更新事件的代码如下.

Hi i am working with asp.net gridview, i have written the code for insert,update,delete and cancel events. All the events code working fine except update event. When debugging my app it shows the error like Object reference not set to an instance of an object.


The code for update event as follows.

protected void grdvEmp_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            //int Id = Convert.ToInt32(grdvEmp.DataKeys[e.RowIndex].Value);
            TextBox txtSample1 = grdvEmp.Rows[e.RowIndex].FindControl("txtEname ") as TextBox;
            TextBox txtSample2 = grdvEmp.Rows[e.RowIndex].FindControl("txtSal") as TextBox;
            Label lblId = grdvEmp.Rows[e.RowIndex].FindControl("lblEmpno") as Label;
                      
            con = new SqlConnection(connectionstring);
            // *** Error occurs on next line
            cmd=new SqlCommand("update EMP set  ENAME='"+txtSample1.Text+"',SAL="+txtSample2.Text+" WHERE EMPNO="+lblId.Text+"",con);
            con.Open();
            cmd.ExecuteNonQuery();
            con.Close();

            grdvEmp.EditIndex = -1;
            BindData();

        }


请给这个问题的解决方案.

谢谢
拉杰什

[edit]已添加代码块-OriginalGriff [/edit]


Plz give solution for this problem.

Thanks
Rajesh

[edit]Code blocks added - OriginalGriff[/edit]

推荐答案

发生此错误的三个可能原因:txtSample1,txtSample2或lblId为空.显而易见,但确实如此.

我从您的代码示例中猜测,它是txtSample1,并且您要搜索的名称中不应有空格:
There are three possible reasons why this error occurs: txtSample1, txtSample2, or lblId are null. Obvious, but true.

I am guessing from your code sample, that it is txtSample1, and that there should not be a space in the name you are searching for:
TextBox txtSample1 = grdvEmp.Rows[e.RowIndex].FindControl("txtEname ") as TextBox;

成为

TextBox txtSample1 = grdvEmp.Rows[e.RowIndex].FindControl("txtEname") as TextBox;


但是,检查这些内容是一个非常非常好的主意:在执行as强制转换之后,始终测试null,以确保您认为的内容确实在起作用...

此外,请不要串联字符串:您可能会因意外或蓄意的SQL注入攻击而敞开大门,这可能会破坏或破坏数据库.改为使用参数化查询.


However, it is a very, very good idea to check these things: Always test for null after you do an as cast, to ensure that what you think is going in, is actually going in...

In addition, never concatenate your strings: you leave yourself wide open for an accidental or deliberate SQL injection attack which could corrupt or destroy your database. Use parametrized queries instead.


这篇关于错误:对象引用未设置为对象的实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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