Showing tool tip for every item in datagridview ro

2019-03-22 16:35发布

问题:

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?

回答1:

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.



回答2:

I have done this by storing the text to show in the tooltip for each cell in the Tag property of each DataGridViewCell.

Then in the DataGridView.CellMouseEnter event you can see in which cell the mouse is using the DataGridViewCellEventArgs.ColumnIndex and DataGridViewCellEventArgs.RowIndex values and set the text from the corresponding cell as the tooltip text using ToolTip.SetToolTip.

If works pretty well.

Something like this:

private void dgv_CellMouseEnter(object sender, DataGridViewCellEventArgs e)
{
    if (e.ColumnIndex >= 0 & e.RowIndex >= 0) 
    {
        ToolTip1.SetToolTip(dgv, Convert.ToString(dgv.Item(e.ColumnIndex, e.RowIndex).Tag));
    }
}


回答3:

When filling the datagridview, just set the TooltipText property of the cell to the text you want to display.