Click here to Skip to main content
15,920,005 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
i am trying to delete userid and groupid from the roles table on selecting userid from the user table in the gridview control. i am getting and error that. can anyone figure out wots the problem in query.

Object reference not set to an instance of an object.



C#
protected void _rowdeleting(object sender, GridViewDeleteEventArgs e)
   {
       GridViewRow row = (GridViewRow)GridView1.Rows[e.RowIndex];
       Label lbldeletename = (Label)row.FindControl("lblusername");
       TextBox textname = (TextBox)row.FindControl("txtusername");
       MAconn.Open();
       SqlCommand cmd = new SqlCommand("Delete From ROLES (UserId,GroupId) SELECT UserId FROM Users WHERE username= '" + textname.Text + "'", MAconn);
       cmd.ExecuteNonQuery();
       MAconn.Close();
       bind();

   }
Posted
Comments
Prerak Patel 9-Sep-11 7:00am    
Debug step by step and check if anything is null.

lbldeletename, textname or MAconn is most likely null, as Prerak suggests use the debugger to the exact reason.
Have a look at Mastering Debugging in Visual Studio 2010 - A Beginner's Guide[^]

I just noticed you're not even using lbldeletename that leaves textname or MAconn as the possible source of your exception.
 
Share this answer
 
v2
I will like to advise to set username as DataKey of Gridview

and do coding something like it.
C#
protected void _rowdeleting(object sender, GridViewDeleteEventArgs e)
    {
         string username= GrdView1.DataKeys[e.RowIndex].Value.ToString();
        MAconn.Open();
        SqlCommand cmd = new SqlCommand("Delete From ROLES (UserId,GroupId) SELECT UserId FROM Users WHERE username= @username", MAconn);
          cmd .Parameters.AddWithValue("@username",username);
        cmd.ExecuteNonQuery();
        MAconn.Close();
        bind();
 
    }
 
Share this answer
 
v2
 
Share this answer
 
Comments
Simon Bang Terkildsen 9-Sep-11 7:06am    
The problem isn't how to use the event. The problem is the code in the event handler.

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