Search code examples
c#asp.netms-accessgridviewdelete-row

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


I have a gridview which populates its data from a MS Access Database. I have enabled the "Selecting" on the gridview, and have created a delete button. 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. 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();"

Webservice method: //Modifies the datbase

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

Solution

  • Your myDataSet is probably being lost after the postback. You must have to save the myDataSet in page's ViewState in order to retain it's value across postbacks. 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.