无法删除,使用gridview更新

时间:2015-04-29 04:39:50

标签: c# asp.net gridview

每次我运行程序并点击gridview中的删除按钮时我都会遇到此异常

  

对象引用未设置为对象的实例

并指出" 这是我的代码,我在我的按钮中使用这两种方法,数据被提取但无法在gridview中删除或更新。

private void getdatafromdb()
{
    string cs = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
    SqlConnection con = new SqlConnection(cs);

    string str = "select * from person";
    SqlDataAdapter da = new SqlDataAdapter(str, con);
    DataSet ds = new DataSet();

    da.Fill(ds, "person");
    ds.Tables["person"].PrimaryKey = new DataColumn[] { ds.Tables["person"].Columns["id"] };

    Cache.Insert("dataset", ds, null, DateTime.Now.AddMinutes(50), System.Web.Caching.Cache.NoSlidingExpiration);

    GridView1.DataSource = ds;
    GridView1.DataBind();
    lblmsg.Text = "DAta loaded from database";
}

private void getdatafromcache()
{
    if (Cache["dataset"] != null)
    {
        DataSet ds = (DataSet)Cache["dataset"];
        GridView1.DataSource = ds;
        GridView1.DataBind();
    }
}

protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
    if (Cache["dataset"] != null)
    {
        DataSet ds = (DataSet)Cache["dataset"];
        DataRow dr = (DataRow)ds.Tables["person"].Rows.Find(e.Keys["id"]);

        dr.Delete();   // <- here it throws an exception

        Cache.Insert("dataset", ds, null, DateTime.Now.AddHours(24), System.Web.Caching.Cache.NoSlidingExpiration);

        getdatafromcache();
    }
}

0 个答案:

没有答案