Showing tool tip for every item in datagridview row when mouse is above it

Enigma State picture Enigma State · Aug 24, 2011 · Viewed 58.4k times · Source

How can you show the tooltip for datagridview for every item in datagridview when you hover mouse over the item in that particular row?

I have table product with columns:

product name 
product price 
product description
product image ....

I have a requirement that I have a datagridview with columns and I am getting these from database:

product name 
product price 
product image ....

Now I want to show the tooltip like this: if I have mouse over the product image, the product description will be displayed for that product. I want to do this for every row. Would anyone please help on this one?

Answer

Jay Riggs picture Jay Riggs · Aug 24, 2011

Take a look at the DataGridViewCell.ToolTipText property and use the DataGridView's CellFormatting event to set this property value. You can use the event's DataGridViewCellFormattingEventArgs ColumnIndex property to determine if the event is firing for the column you want to set a tool tip for and if so use the event's RowIndex to specify that tool tip's value.

The sample in the MSDN article I linked have a fine example of usage, but your code might look something like this:

private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e) {
    if (e.ColumnIndex == dataGridView1.Columns[nameOrIndexOfYourImageColumn].Index) {
        var cell = dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex];
        // Set the Cell's ToolTipText.  In this case we're retrieving the value stored in 
        // another cell in the same row (see my note below).
        cell.ToolTipText = dataGridView1.Rows[e.RowIndex].Cells[nameOrIndexOfYourDescriptionColumn].Value.ToString();
    }
}

Where:
nameOrIndexOfYourImageColumn = the column name or index value of your image column nameOrIndexOfYourDescriptionColumn = the column name or index value with your description data.

Note: that you'll need some way to retrieve a row's Description data. A common way to do this is to have a column for it in your DataGridView, but make since you don't want to display this column set its Visible property to false. There are other options however.