Microsoft Communities

Welcome to WindowsClient.net | Sign in | Join

Here are some frequently asked questions about Windows Forms and their answers.

Windows Forms FAQs

How do I get tooltips to vary by cell in a DataGrid?

One way to do this is to use a ToolTip control and reset the control text as the mouse moves across cells. Below is a derived DataGrid class that implements this idea. The main points are:

Have members that track the current hitRow and hitCol where the mouse is.

In a MouseMove handler, do a HitTest on the mouse location to see if there is a new hit cell. If so, set the hitRow & hitCol, and hook the tooltip to hold your text according to the cell. In our sample, we just display the string value of the grid cell.

Finally, in the MouseMove handler, after setting a new text in the tooltip, set the tooltip active so it can show itself in due time.

using System.Windows.Forms;

public class DataGridToolTips : DataGrid
{
  private ToolTip toolTip1;
  private int hitRow;
  private int hitCol;

  public DataGridToolTips()
  {
    hitRow = -1;
    hitCol = -1;
    toolTip1 = new ToolTip();
    toolTip1.InitialDelay = 1000;
    MouseMove += new MouseEventHandler( HandleMouseMove );
  }

  private void HandleMouseMove( object sender, MouseEventArgs e )
  {
    DataGrid.HitTestInfo hti = HitTest( new Point( e.X, e.Y ) );
    if ( hti.Type == DataGrid.HitTestType.Cell
        && ( hti.Row != hitRow || hti.Column != hitCol ) )
    {     // new hit row
      hitRow = hti.Row;
      hitCol = hti.Column;
      if ( toolTip1 != null && toolTip1.Active )
        toolTip1.Active = false; // turn it off
      toolTip1.SetToolTip( this, this[ hitRow, hitCol ].ToString() );
      toolTip1.Active = true; // make it active so it can show itself
    }
  }
}

Contributed from George Shepherd's Windows Forms FAQ



Page view counter