Friday, January 18, 2008

Gridview - Delete a row

So, I recently developed an ASP:Gridview to display a list of documents. I was having some problems accessing the datakey of the row that the "delete" button resided in. I looked around a bit, and I found a resolution on the asp.net forums. It turns out that the GridViewDeleteEventArgs object contains the current row index. The DataKeys of the gridview are stored in the same order of the row indexes. You can access the DataKey (which in my case was the document ID number) by getting the GridView.DataKeys[e.RowIndex].

Codebehind event handler for when "delete" button is clicked notice how the event handler event args type is set to "GridViewDeleteEventArgs"
protected void DeleteDocument(object sender, GridViewDeleteEventArgs e)
{         

        int DocID = Convert.ToInt32(this.ListOfDocumentsGridview.DataKeys[e.RowIndex].Value);

        Document.DeleteByID(DocID);

}

No comments: