User Tips: Highlighting a DataGrid Row When Mousing Over
By Mark Mailer
I recently read Scott Mitchell's article
Creating a Row-Selectable DataGrid Control, which
details how to create a custom DataGrid server control whose rows' background colors change when moused over and whose rows
can be selected by clicking anywhere in the row. (You can see a live
demo of Scott's control here.)
Rather than use Scott's custom control, I wanted a quick and easy way to add row-level highlighting when mousing over a
particular DataGrid in a particular ASP.NET page. My solution was to directly add onmouseover and
onmouseout attributes to the DataGrid's items in the ItemDataBound event handler.
My code is used in an intranet, IE-only setting and has worked well. While not as robust as Scott's approach, it can be
quickly and easily implemented.
Anyway, the code for the DataGrid's ItemDataBound event handler is provided below:
Private Sub DataGridID_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.DataGridItemEventArgs) Handles DataGridID.ItemDataBound
If e.Item.ItemType = ListItemType.Item OrElse e.Item.ItemType = ListItemType.AlternatingItem Then
' Do the mouseover and mouseout javascript
Dim oBGcolour As String
If e.Item.ItemType = ListItemType.Item Then
oBGcolour = Right(Hex(DataGridID.ItemStyle.BackColor.ToArgb()), 6)
ElseIf e.Item.ItemType = ListItemType.AlternatingItem Then
oBGcolour = Right(Hex(DataGridID.AlternatingItemStyle.BackColor.ToArgb()), 6)
End If
e.Item.Attributes.Add("onmouseover", "this.style.background='#cdcdcd';")
e.Item.Attributes.Add("onmouseout", "this.style.background='#" & oBGcolour & "';")
End If
End Sub
|
Happy Programming!
By Mark Mailer