Search code examples
vb.netdatagridviewtooltip

Windows Form Tooltip won't display on datagridview on initial cell edit


I'm trying to display a tool tip on a datagridview as the user is editing the cell. My problem is that the tool tip isn't displaying when the cell is being edited for the first time. For example, if I type "=2*10" into the cell the tool tip doesn't display, BUT if I were to then leave the cell, re-enter, and continue typing then the tool tip shows up (with the correct text and in the correct location). So I'm wondering why the tool tip doesn't show up on the initial edit. Answers in C# are acceptable as well as changing the syntax between C# and VB is trivial. In this case, the variable 'obj' in the code refers to a datagridview object.

' obj is datagridview object 

' hide tool tip on Enter key press
If keyData = Keys.Enter Then
        ToolTip1.Hide(obj)
        obj.ShowCellToolTips = True

' Check if cell is empty
ElseIf (obj.Item(obj.CurrentCell.ColumnIndex, obj.CurrentRow.Index).Value IsNot Nothing) Then
        Debug.Print(obj.Item(obj.CurrentCell.ColumnIndex, obj.CurrentRow.Index).Value.ToString)

        ' Check if current cell starts with "="
        If obj.Item(obj.CurrentCell.ColumnIndex, obj.CurrentRow.Index).Value.ToString.StartsWith("=") Then
            If obj.IsCurrentCellInEditMode Then

                Dim RowHeight1 As Integer = obj.Rows(obj.CurrentRow.Index).Height
                Dim CellRectangle1 As Rectangle = obj.GetCellDisplayRectangle(obj.CurrentCell.ColumnIndex, obj.CurrentRow.Index, False)

                CellRectangle1.X += obj.Left
                CellRectangle1.Y += obj.Top 

                Dim displayPoint As Point = PointToScreen(New Point(CellRectangle1.X, CellRectangle1.Y))

                obj.CommitEdit(DataGridViewDataErrorContexts.Commit)
                obj.ShowCellToolTips = False
                ToolTip1.Show("This is a test", obj, displayPoint)
            End If

        Else 
            ToolTip1.Hide(obj)
            obj.ShowCellToolTips = True
        End If
End If

Solution

  • Having recreated your problem I can see that the call here:

    obj.Item(obj.CurrentCell.ColumnIndex, obj.CurrentRow.Index).Value
    

    Is not retrieving the value you expect. It is providing the unedited value, the value that is saved after edit/validation.

    If you change this call (in all places) to be:

    obj.Item(obj.CurrentCell.ColumnIndex, obj.CurrentRow.Index).EditedFormattedValue
    

    it works great.