Adding Tooltips to Datagrid Rows

Adding a tooltip to a DataGrid row can provide additional information about the entry. The space available within the pop-up is likely larger than that within the row cell.

The tooltip allows for a minimal presentation on the DataGrid rows, ensuring that the information presented is succinct and easy to follow.

I like to use the ItemDataBound event handler to add tooltips to DataGrid rows. This allows more control over the content.

The DataGrid layout structure is defined in the in the .ascx file. Columns and rows are defined with references to the database fields.

Shown below is the DataGrid definition in the .ascx file.

<asp:datagrid id="grdFruit"
AllowPaging="False"
AutoGenerateColumns="False"
runat="server"
">
<Columns>
<asp:TemplateColumn HeaderText="Status" HeaderStyle-CssClass="subhead">
<ItemTemplate>
<asp:Label id="RefId" Text='<%# DataBinder.Eval(Container,"DataItem.RefId") %> ' Visible= "False" runat= "server" Visible="False"></asp:Label>
<asp:Label id="Name" Text='<%# DataBinder.Eval(Container, "DataItem.name") %> 'runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateColumn>
</Columns>
</asp:datagrid>

In the associated code behind file, functions exist to bind the DataGrid to the database and to perform an action when each row is bound: ItemDataBound.

Dependant upon the implementation and the relevant clauses, the tooltip content may either be derived within the ItemDataBound function or derived on the SQL and stored as a hidden field.

I often have a column where I sneak these hidden items in, a status column is a good one. Note the row below where the value of the id is taken from the database.

The value of the reference, RefId, to be used for our tooltip, therefore ensures that it is available in the column definitions.

Considering the code behind file .ascx.vb. A sub-routine is required to handle the ItemDataBound event of the DataGrid and that the handling of row highlighting is working.

Following the addition of the events for the row colours we need to add one more for our tooltip.

Private Sub grdFruit_OnItemBound(ByVal sender As Object, ByVal e As DataGridItemEventArgs) Handles grdFruit.ItemDataBound
  Try
    If (e.Item.ItemType = ListItemType.Item) Or (e.Item.ItemType = ListItemType.AlternatingItem) Then
      e.Item.Attributes.Add("onmouseover","this.style.backgroundColor='lemonchiffon';this.style.cursor='hand'")
      e.Item.Attributes.Add("onclick", "javascript:window.location.href='" & EditUrl("RefID", CType(e.Item.FindControl("RefId"), Label).Text, "Edit_short") & "'")
      e.Item.ToolTip = "Ref: " & CType(e.Item.FindControl("RefId"), Label).Text
    End If
  Catch
  End Try
End Sub

The table below is an example of the results from the above.

Plums
Apples

In this example hidden fields were added to the DataGrid rows. These fields were then used when adding the tooltips to the row during the OnItemBound process.