【问题标题】:ASP.NET Getting value from gridviewASP.NET 从 gridview 中获取价值
【发布时间】:2017-04-25 14:33:08
【问题描述】:

这是我的代码

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:对象引用未设置为对象的实例。

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

【问题讨论】:

标签: c# asp.net


【解决方案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 的最可能原因是触发 RowDeleting 事件时未设置 SelectedRow 属性。

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

【讨论】:

    猜你喜欢
    • 2022-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-02
    • 2020-12-20
    • 2017-05-24
    相关资源
    最近更新 更多