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

本文关键字:删除 net Asp 一行 Gridview 选择 | 更新日期: 2023-09-27 18:11:48

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

我得到的错误是"对象引用不设置为对象的实例",在代码行中,它说,"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);
}

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

您的myDataSet可能在回发后丢失。你必须保存myDataSet在页面的ViewState为了保留它的值跨回发。这样的:

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

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