Introduction

The ASP.NET GridView is an excellent control and is widely used, but still lacks some features. This article demonstrates extending the GridView to add cell click event handling by inheriting from the base GridView class, overriding and changing some of the properties and behaviour.

Background

After doing some research, there seems to be not a lot of resources with regards to cell click event handling in the ASP.NET GridView. I have found one or two articles where you have to add some JavaScript functions to the RowDataBound() event of the GridView. I wanted an out-of-the-box gridview with this functionality. Finally, I came across a blog post by Jonni Teemu Keiski called Developing a row-clickable GridView, and started from there by applying the same principle to the cells of the GridView.

Using the code

Adding a designer property: Enable cell-click

Since we opt to have a generic control, we add a property that the programmer can set to enable postback events when a cell is clicked.

Adding a class for the arguments of the cell-click event

In order to return the properties of the cell that was clicked, we create a new custom event argument that inherits the base event argument class. We will return the custom event argument in the custom event handler CellClicked() that we'll create in the next section.

Adding the attributes of the base control (GridView) to the child controls (TableCell)

The next step is to apply the click event and event arguments to the child control which is the TableCell of the GridView. This is done by overriding the PrepareControlHierarchy() method of the base class.

Handling the postback

Finally, we override the RaisePostBackEvent() event. In this method, the GridView's events are raised when a postback happens on the server. We will override the method to determine from the EventArgument whether the event was caused by clicking a cell. From here, we use the event data to create a new instance of GridViewCellClickedEventArgs and pass it to the OnCellClicked() method.

Comments and Discussions

This is a very cool control. Thanks for publishing it.
Is there a way to retrieve the column header of the cell clicked?
I can retrieve any cell from a row clicked by using
Dim Cell1 As String = e.Row.Cells(0).Text

But I wouold like to get a value of the HeaderText for the Cell clicked.