0

我正在尝试从 Datagrid 中删除行。我使用 Ilist 作为数据源。我已经在 DataGrid_Rowdeleting 事件中初始化了 IList 对象,但同样的异常仍然困扰着我。请帮帮我。我的代码如下

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections;
using System.Data;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            IList lst = new ArrayList();
            Session["lst"] = lst;
        }
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        Class1 c = new Class1();
        c.product = txtName.Text;
        c.quantity = txtQty.Text;
        IList lst = (IList)Session["lst"];
        lst.Add(c);
        GridView1.DataSource = lst;
        GridView1.DataBind();

    }
    protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
       DataTable dt = new DataTable();
       dt = (DataTable)GridView1.DataSource;
        dt.Rows.RemoveAt(e.RowIndex);
        GridView1.DataSource = dt;
        GridView1.DataBind();
    }

    protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
    {

    }
}
4

2 回答 2

1

问题在这里:

dt = (DataTable)GridView1.DataSource;

DataSource只有在页面生命周期的前面步骤中明确设置时才为空。在您的情况下,它在回发期间未设置任何位置(由删除命令触发),因此DataSource为空。

处理此问题的正确方法是在数据库中运行必要的删除查询,检索更新的信息并重新绑定网格。

于 2013-07-24T09:34:12.277 回答
0

试试这个

protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
   IList lst = (IList)Session["lst"];
   lst .RemoveAt(e.RowIndex);
    GridView1.DataSource = lst ;
    GridView1.DataBind();
}
于 2013-07-24T09:47:17.290 回答