DataGridView: Find if ColumnHeaders are actually visible

How do I know if the column headings are visible in Datagridview

?

Since the control is Datagridview

not disabled when disabled when disabled, I am trying to emulate this by drawing a little padlock icon in the upper left corner. Since it looks bad if drawn over the column headers, I want to move them below them.

However, I found that neither the properties ColumnHeadersVisible

nor ColumnHeadersHeight

did they give exact values ​​in all cases. Sometimes they are executed first, but after adding and removing data, the property is wrong again.

This can be easily reproduced by adding the following class to a new project, running the project once, and adding the control NewDGV

to the form. Even in the constructor, you can see that the rectangle is being drawn in the wrong place.

Public Class NewDGV
    Inherits DataGridView

    Protected Overrides Sub OnPaint(e As PaintEventArgs)
        MyBase.OnPaint(e)

        Dim y As Integer = 0
        'Get the location to draw a rectangle to
        If Me.ColumnHeadersVisible Then
            'y = Me.ColumnHeadersHeight + 1 gives the wrong value as well
            y = Me.GetCellDisplayRectangle(-1, -1, False).Height + 1
        Else
            y = 1
        End If
        e.Graphics.FillRectangle(Brushes.Azure, 1, y, 30, 30)
    End Sub
End Class

      

Here is the result without further modification:

enter image description here

As you can see, even if the headers are clearly invisible (there aren't any columns at all), the rectangle is drawn in the wrong place.

Edit: Perhaps I was not completely clear: whenever the column headings are invisible, I want the rectangle to appear in the upper left corner without any extra space. When the column headers are visible, I want the rectangle to appear below the header cells (this means that it is drawn with a pixel distance ColumnHeadersHeight

from the vertex).

How can I fix this and find if the column headers are actually visible?

The answers in both VB.NET and C #, whichever you prefer, are greatly appreciated.

+3


source to share


1 answer


Not sure if this works under all circumstances - check the property FirstDisplayedCell

:



  Protected Overrides Sub OnPaint(e As PaintEventArgs)
    MyBase.OnPaint(e)
    Dim y As Integer = 0
    'Get the location to draw a rectangle to'
    If Me.ColumnHeadersVisible And Me.FirstDisplayedCell IsNot Nothing Then
      '                        ---------------------------------------
      ' 
      y = Me.GetCellDisplayRectangle(-1, -1, False).Height + 1
    Else
      y = 1
    End If
    e.Graphics.FillRectangle(Brushes.Azure, 1, y, 30, 30)
  End Sub

      

+1


source







All Articles