ASP.NET - Error occured while deleting the row of gridview on row deleting event

Asked By aman on 24-Nov-11 02:48 AM
Hello all
I have used the below snipped code for the same
but the strQuestion always have the null values thatswhy row cannot be delete.

protected



void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)

{


string strQuestion = GridView1.Rows[e.RowIndex].Cells[0].Text.ToString();


SqlConnection ObjConnection = new SqlConnection(strConnection);

ObjConnection.Open();


SqlCommand ObjCommand = new SqlCommand("delete from tblQnA where Question = '" + strQuestion + "'", ObjConnection);

ObjCommand.ExecuteNonQuery();

ObjConnection.Close();

LoadGrid();

}


Please Help me
dipa ahuja replied to aman on 24-Nov-11 02:54 AM
Try this protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
  int id = int.Parse(((Label)GridView1.Rows[e.RowIndex].FindControl("lblid")).Text);//ID
 
  SqlConnection connect = new SqlConnection(ConnString);
  connect.Open();
 
  string q = "Delete from table where id=@id";
 
  SqlCommand comm = new SqlCommand(q, connect);
  comm.Parameters.AddWithValue("id", id);
  comm.ExecuteNonQuery();
  connect.Close();
 
  GridView1.EditIndex = -1;
 
    //Code to bind gridview
}
Reena Jain replied to aman on 24-Nov-11 03:11 AM
hi,

here is the code for you to delete the row from gridview
01  protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
02    {
03    GridViewRow row = (GridViewRow)GridView1.Rows[e.RowIndex];
04    Label lbldeleteID = (Label)row.FindControl("lblid");
05    conn.Open();
06    SqlCommand cmd = new SqlCommand("delete  emp where rowid=" + lbldeleteID.Text + "", conn);
07    cmd.ExecuteNonQuery();
08    conn.Close();
09    //rebind the griview with updated data
10    }

Hope this will help you
Jitendra Faye replied to aman on 24-Nov-11 03:30 AM
Try like this-

Code to delete

protected void GridView2_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
      string strEmpId = GridView1.Rows[e.RowIndex].Cells[1].Text;   //FOR GETTING ENPID
 
      string deleteQuery = "delete from emp  where empid= ' " + strEmpId + " ' ";
      SqlConnection cn = new SqlConnection("CONNECTION STRING");
      cn.Open();
      SqlCommand cmd = new SqlCommand(deleteQuery, cn);
      cmd.ExecuteNonQuery();
      cn.Close();
      GridView1.EditIndex = -1;
      Response.Write("<script>alert('Record Deleted')</script>"); 
       getdata();
      
    }