Search code examples
c#datagridviewtooltip

Show ToolTip on DataGridView when cell value has changed


I want to show a ToolTip when the value of a cell in a DataGridView control is changed and the introduced value is invalid.

This can easily be done with the code below, but the problem is that after the ToolTip is shown, it is also associated with the control, so every time the DataGridView is hovered the ToolTip is displayed, and I want it to be shown only once after the data has been changed.

I have noticed that this happens only with DataGridView and GroupBox. With a TextBox or a Button the ToolTip is not associated with the control when shown over it.

Why does this happen?

    public partial class Form1 : Form
    {
        this.dataGridView1.ShowCellToolTips = false; // so we can show regular tooltip
    }
    private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
    {
        DataGridView control = (DataGridView)sender;
        // check if control.Rows[e.RowIndex].Cells[e.ColumnIndex].Value is valid
        if (invalid)
        {
            toolTip.Show("Invalid data", dataGridView1, 5000);
        }
    }

Solution

  • There are many ways to deal with this. The simplest and most direct seems to be to Hide the ToolTip when you are leaving the DataGridView:

    private void dataGridView1_Leave(object sender, EventArgs e)
    {
        toolTip1.Hide(this);
    }
    

    Of course it is up to you to decide upon the full design of what should happen while the error is still there..!

    As for Textboxes: They are very special and there is usually no use in asking why they behave diffently..

    Another way would be to code the Popup event and use the Tag as a flag to make sure it is shown only once:

    Before you show it in the CellValueChanged you set a flag:

     toolTip1.Tag = "true";
    

    and in the Popup event you check for it:

    private void toolTip1_Popup(object sender, PopupEventArgs e)
    {
        if (toolTip1.Tag == null) return;
        bool show = toolTip1.Tag.ToString() == "true";
        if (toolTip1.Tag != "true") e.Cancel = true;
        toolTip1.Tag = "false";
    }