0

Here is my code

protected void GridView1_DeletingRow(object sender, EventArgs e)
    {
        Functions con = new Functions();
        SqlConnection con1 = con.get();
        con1.Open();
        TextBox1.Visible = true;
        Button1.Visible = true;
        string z = TextBox1.Text;
        GridView1.EnableViewState = true;
        string name = GridView1.SelectedRow.Cells[1].Text;
        SqlCommand com3 = new SqlCommand("select id from products where product 
        = '" + name + "' ", con1);
        SqlDataReader read1 = com3.ExecuteReader();
        read1.Read();
        string pro = read1["id"].ToString();
        SqlCommand com = new SqlCommand("UPDATE CartItems SET quantity = '" + z 
        + "' where productid = '" + pro + "' ", con1);
    }

Error :

Line 92:  string name = GridView1.SelectedRow.Cells[1].Text;

Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

What is the error exactly? , and how can I fix it ?

  • 3
    Possible duplicate of [What is a NullReferenceException, and how do I fix it?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – Rick S Apr 25 '17 at 14:38

1 Answers1

1

You should change your EventArgs parameter to the more-specific GridViewDeleteEventArgs type, and use that to find the row being deleted:

protected void GridView1_DeletingRow(object sender, GridViewDeleteEventArgs e)
{
    // ...your code
    string name = GridView1.Rows[e.RowIndex].Cells[1].Text;
    // ...the rest of your code

The most likely reason for your NullReferenceException is because the SelectedRow property is not set when the RowDeleting event is fired.

Note: it's also possible that "Cells[1].Text" could throw that exception, if your grid only has one column. You should review the advice in this post that can help you with debugging NullReferenceExceptions.

Community
  • 1
  • 1
Josh Darnell
  • 11,304
  • 9
  • 38
  • 66