@ASP.NET Forums: How to develop a row-clickable DataGrid control?
As subject tells, this one was asked at Forums. Of course, such is easy to write using built-in features of DataGrid when you place Button controls on templates and catch ItemCommand event, however if you want to catch the click from entire row area, you ened to do some work. It's a good candidate for being a custom control, for example, which catches clicks targeted at DataGrid rows (rows of the rendered HTML table).
Here is a very simple example I wrote about in 3 minutes. Therefore it is very raw and you could make it better in many ways, however, it also effectively demonstrates how easy this is to achieve and how powerful DataGrid actually is.
Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.WebControls
Public Class Clickablegrid
Inherits DataGrid
Implements IPostBackEventHandler
'Event which is raised when a row is clicked
Public Event ItemClicked(ByVal sender As Object, ByVal e As EventArgs)
'Method to raise the event
Protected Overridable Sub OnItemClicked(ByVal sender As Object, ByVal e As EventArgs)
RaiseEvent ItemClicked(sender, e)
End Sub
'When items are created, add the script to cause a postback
'with item index as argument
Protected Overrides Sub CreateControlHierarchy(ByVal useDataSource As Boolean)
MyBase.CreateControlHierarchy(useDataSource)
Dim i As Integer
For i = 0 To Items.Count - 1
Me.Items(i).Attributes.Add("onclick", Page.GetPostBackEventReference(Me, i.ToString()))
Next
End Sub
'When a row is clicked, this is called and event will be raised
'with the specific item as sender of the event
Public Sub RaisePostBackEvent(ByVal eventArgument As String) Implements System.Web.UI.IPostBackEventHandler.RaisePostBackEvent
If Not eventArgument Is Nothing Then
Dim i As Integer = Int32.Parse(eventArgument)
OnItemClicked(Me.Items(i), EventArgs.Empty)
End If
End Sub
End Class
And usage example
<cc1:Clickablegrid id="Clickablegrid1" runat="server" />
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
If Not Page.IsPostBack Then
Dim a As New ArrayList
a.Add(1)
a.Add(2)
a.Add(3)
Clickablegrid1.DataSource = a
Clickablegrid1.DataBind()
End If
End Sub
Private Sub Clickablegrid1_ItemClicked(ByVal sender As Object, ByVal e As System.EventArgs) Handles Clickablegrid1.ItemClicked
Response.Write("Index of the clicked item was: " & CType(sender, DataGridItem).ItemIndex)
End Sub