2017-04-25 51 views
0

值这里是我的代码ASP.NET充分利用GridView的

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); 
    } 

错误:

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

异常详细信息:System.NullReferenceException:对象不设置到对象的实例。

究竟是什么错误? ,我该如何解决它?

+3

可能重复[什么是NullReferenceException,以及如何解决它?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-doi-i-fix -it) –

回答

1

您应该将EventArgs参数更改为更具体的GridViewDeleteEventArgs类型,并用它来找到该行被删除:

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

您的NullReferenceException最可能的原因是因为SelectedRow属性未设置RowDeleting事件被触发时。

注意:如果您的网格只有一列,“Cells[1].Text”也可能会引发该异常。您应该查看this post中的建议,它可以帮助您调试NullReferenceExceptions。

+0

工作! ,非常感谢:D –