Search code examples
c#.netwinformsdatagridviewtooltip

datagridview mousehover event how to determine which column you are on


I want to display a tooltip when I mousehover over a column header on my datagridview control (dgrv1). Currently, I can do the following, which works -- but -- my datagridview has several columns (and a lot of text for each tooltip), so I would like to call a method from the mousehover event. My problem is that I don't know how to capture which column I am hovering over to pass in to the method. Interestingly, the mousehover event picks the correct column in my current scenario:

private void dgrv1_MouseHover(object sender, EventArgs e)
{  
    dgrv1.Columns[1].ToolTipText = "column 1";
    dgrv1.Columns[2].ToolTipText = "column 2";
    dgrv1.Columns[3].ToolTipText = "column 3";
}

If I mousehover over column 1 -- the tooltiptext for column 1 gets displayed, and the same for columns 2, 3, ... But instead of listing 50 columns (which the tooltips would contain quite a bit of text) in the mousehover event here, how could I just call a method from the mousehover event and pass in the correct column number?


Solution

  • You don't need to assign ToolTipText property of your columns in hover event. you simply can assign them using Designer or if you want when you load data or load event of form using such code:

    foreach (DataGridViewColumn c in this.dataGridView1.Columns)
    {
        c.ToolTipText = string.Format("Column {0}", c.Index + 1);
    }
    

    You can also assign a text to ToolTip property of a cell:

    this.dataGridView1.Rows[0].Cells[0].ToolTipText = "Some text"
    

    But if you want to know what is the column and row that mouse is hover on it, you can use HitTest method of DataGridView:

    private void dataGridView1_MouseHover(object sender, EventArgs e)
    {
        var p = this.dataGridView1.PointToClient(Cursor.Position);
        var info = this.dataGridView1.HitTest(p.X, p.Y);
    
        //You can use this values
        //info.ColumnX
        //info.RowY
        //info.ColumnIndex
        //info.RowIndex
    }
    

    Pay attention that RowIndex is -1 for column header cells and ColumnIndex is -1 for row header cells.