Click here to Skip to main content
16,021,211 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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.

C#
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();

        }

Plz give solution for this problem.

Thanks
Rajesh

[edit]Code blocks added - OriginalGriff[/edit]
Posted
Updated 17-Aug-11 8:04am
v3
Comments
Rajjjjjjj 17-Aug-11 14:31pm    
Thanks alot. Thank you so much for giving solution.
Problem solved.
Again a small problem here when i am changing the data and then clicking on "update" it shows the previous data instead of modified data.
What would be the problem.
---------------------------
Thanks
Rajesh

1 solution

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:
C#
TextBox txtSample1 = grdvEmp.Rows[e.RowIndex].FindControl("txtEname ") as TextBox;
Becomes
C#
TextBox txtSample1 = grdvEmp.Rows[e.RowIndex].FindControl("txtEname") as TextBox;

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.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900