1

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

我得到的错误是“对象引用未设置为对象的实例”,代码行中显示“myDataSet.Tables [“Users”].Rows[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);
}
4

1 回答 1

1

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

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

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

于 2013-05-01T23:09:21.150 回答