[英]Deleting row from GridView, Object not set to an object reference
I am trying to delete row from Datagrid. 我正在尝试从Datagrid删除行。 I am using Ilist as a datasource. 我正在使用Ilist作为数据源。 I already initialised IList object in DataGrid_Rowdeleting event but still same exception is harrasing me. 我已经在DataGrid_Rowdeleting事件中初始化了IList对象,但是仍然有同样的异常困扰着我。 Please help me out. 请帮帮我。 My code is as below 我的代码如下
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)
{
}
}
Problem is here: 问题在这里:
dt = (DataTable)GridView1.DataSource;
DataSource
is not null only when set explicitly in previous steps of the page life cycle. 仅当在页面生命周期的先前步骤中明确设置了DataSource
为null。 In your case it was not set anywhere during postback (which was triggered by delete command), thus DataSource
is null. 在您的情况下,在回发过程中未设置任何位置(由delete命令触发),因此DataSource
为null。
Correct way to handle this is to run necessary delete query in the DB, retrieve updated info and rebind the grid. 解决此问题的正确方法是在数据库中运行必要的删除查询,检索更新的信息并重新绑定网格。
Try This one 试试这个
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
IList lst = (IList)Session["lst"];
lst .RemoveAt(e.RowIndex);
GridView1.DataSource = lst ;
GridView1.DataBind();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.