在Gridview中选择一行并删除它 - Asp.net

时间:2013-05-01 22:31:38

标签: c# asp.net ms-access gridview delete-row

我有一个gridview,它从MS Access数据库填充其数据。我在gridview上启用了“选择”,并创建了一个删除按钮。我想在gridview上选择一行,并在按下删除按钮时从gridview和数据库中删除数据。下面是我尝试过的代码,但它不起作用。

我得到的错误是“对象引用没有设置为对象的实例”在代码行中,“myDataSet.Tables [”Users“]。行[i] .Delete();”

Webservice方法: //修改数据库

[WebMethod]
public string DatabaseUserModify(DataSet myDataset) 
{ 
 string database = "Provider=Microsoft.ACE.OLEDB.12.0;DataSource=|DataDirectory|/studentdb.accdb;Persist Security Info=True"; 
 OleDbConnection myConn = new OleDbConnection(database); 
 OleDbDataAdapter myDataAdapter = new OleDbDataAdapter("Select * from Users", 
myConn); 
OleDbCommandBuilder builder = new OleDbCommandBuilder(myDataAdapter); 
 builder.QuotePrefix = "["; 
 builder.QuoteSuffix = "]"; 
 myConn.Open(); 
 myDataAdapter.Update(myDataset, "Forum"); 
 myConn.Close(); 
return "done"; 
} 

网站:

protected void DeleteButton(object sender, EventArgs e)
{
    Service myService = new Service();
    myDataSet = myService.AdminGetUserTable();

    int i = GridView1.SelectedIndex;
    myDataSet.Tables["Users"].Rows[i].Delete();//This is where I am getting error

    GridView1.DataSource = myDataSet;
    GridView1.DataBind();

    myService.DatabaseUserModify(myDataSet);
}

1 个答案:

答案 0 :(得分:1)

你的 myDataSet 可能在回发后丢失了。您必须在页面的 ViewState 中保存 myDataSet ,以便在回发中保留它的值。像这样:

    public DataSet myDataSet 
    {
        get 
        { 
            return ViewState["myDataSet"] != null ? (DataSet)ViewState["myDataSet"] : null; 
        }
        set 
        {
            ViewState["myDataSet"] = value;
        }
    }

但是,在ViewState中保存大型数据/对象是最糟糕的主意。