Thursday, October 16, 2008

Perform actions before a row is deleted from a GridView or a DetailsView

I'm a big fan of caching objects on the web server, really saves loads of unneccessary trips to SQL Server and those precious resources.
In a recent project I built some administration screens to change the configuration of my site, as it happens this data was cached on the server for 8 hours at a time.
Rather than let the cache expire for the changes to be picked up I leveraged a feature of the GridView and DetailsView controls I was using, to clear the cache on a DELETE or INSERT by simply using the RowDeleting Event on the GridView and the ItemInserting on the DetailsView.
Here's the code:

protected void ProductCategoriesGridView_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
string categoryID =((HiddenField)ProductCategoriesGridView.Rows[e.RowIndex].FindControl("CATEGORY_ID")).Value;
try
{
Cache.Remove("PRODUCTS_" + categoryID);
}
catch (Exception)
{
}
}



Using the RowIndex property of the GridViewDeleteEventArgs, you can then access the row that you're just about to delete. Here I have a hidden field that holds a key suffix to a cached object. This isn't a key in my GridView or I would have used the DataKeys property.
When I need to insert some data via the DetailsView I used the following code on the ItemInserting event.


protected void ProductCategoryDetailsView_ItemInserting(object sender, DetailsViewInsertEventArgs e)
{
    string categoryID = ((DropDownList)ProductCategoryDetailsView.Rows[0].FindControl("CategoryDropDownList")).SelectedValue;
  try
    {
         Cache.Remove("PRODUCTS_" + categoryID);
    }
    catch (Exception)
    {
    }
}


Here I'm grabbing the key suffix from a dropdown list in the DetailsView. I clear the cache and perform the INSERT to the database. This will ensure that the latest data is loaded and cached for the next request.

No comments: