WinForms DataGrids and tooltips
Most of my Web datagrids use data-bound tooltips. (This is a feature that I also suggested to add to the ASP.NET 2.0 GridView.) The idea is pretty simple: you use one of the row fields to populate a tooltip control. In Web Forms, I normally achieve this by writing a ItemDataBound handler that does the following:
- Make sure the item being bound is Item or AlternatingItem
- Grab the data item
- Retrieve the control (or the cell) I want to bind to the tooltip
- Set the ToolTip property of that WebControl to one of the data item fields. Normally a cast to WebControl is required because the ToolTip property is not available on the more base class Control.
- When the control renders to HTML, the ToolTip property is rendered as a title property
It (usually) works great.
Today (no such Thanksgiving holiday in Europe...) I needed to achieve the same but for a Windows Forms datagrid. Here's how I did it.
I added a ToolTip control to the form and created a custom table style for my grid. I made the datagrid column object I wanted to use a tooltip with global in the code. Next, the following steps:
- Add a CurrentCellChanged event handler
- Retrieve column and row number for the new cell
- Map the column number to a row in the Rows collection of the underlying DataTable
- Retrieve the data-bound text from the DataRow
- Call ToolTip1.SetToolTip on the TextBox object associated with the grid column
- DataGridTextBoxColumn has a TextBox property that returns the instance of the textbox being used to edit the contents of each cell in the column. It's always the same object just moved around as you click on the cells
- The SetTooltip method on the ToolTip object sets a text to display with a control
It works. And this is enough for me now!