简体   繁体   English

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

[英]Selecting a row in Gridview and deleting it - Asp.net

I have a gridview which populates its data from a MS Access Database. 我有一个gridview从MS Access数据库填充其数据。 I have enabled the "Selecting" on the gridview, and have created a delete button. 我已在gridview上启用“选择”,并创建了一个删除按钮。 I would like to select a row on the gridview and delete the data from the gridview as well as the database when the delete button is pressed. 我想在gridview上选择一行,并在按下Delete按钮时从gridview以及数据库中删除数据。 Below is my attempted code, but its not working. 以下是我尝试的代码,但无法正常工作。

Error that I am getting is "Object reference not set to an instance of an object" on the line of code where it says, "myDataSet.Tables["Users"].Rows[i].Delete();" 我收到的错误是代码行上的“对象引用未设置为对象的实例”,它说:“ myDataSet.Tables [“ Users”]。Rows [i] .Delete();”

Webservice method: //Modifies the datbase 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"; 
} 

Website: 网站:

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);
}

Your myDataSet is probably being lost after the postback. 回发后,您的myDataSet可能会丢失。 You must have to save the myDataSet in page's ViewState in order to retain it's value across postbacks. 您必须将myDataSet保存在页面的ViewState中,以便在回发中保留其值。 Like this: 像这样:

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

But, it is a worst idea to save large data/objects in a ViewState. 但是,将大型数据/对象保存在ViewState中是最糟糕的主意。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM