当RowCount = 1时,调整DataGridView的大小将无法正常工作

时间:2016-07-18 10:35:41

标签: vb.net datagridview resize

我编写了一个代码来调整(和调整)DataGridView到他的内容 代码正常工作,DataGridView.RowCount = 1除外。

当只有一行时,水平滚动条出现并隐藏带有数据的行。

我运行了很多调试但是无法理解错误的位置。

我解决了添加一个If(当只有一行时向Width添加2个像素)但不是解决方案而且我想知道我哪里错了。
这是我的代码:

Private Function DGV_Adapt(ByVal DGV_Name As String, ByVal RifCtrl_Name As String) As Boolean
    Dim adapted As Boolean
    Try
        Dim DGV As DataGridView = DirectCast(Me.Controls(DGV_Name), DataGridView)
        Dim RifCtrl As Control = Me.Controls(RifCtrl_Name)
        'Check screen size
        Dim ScreenDims As Rectangle = Screen.GetWorkingArea(New Point(0, 0))
        Dim MaxWidth As Integer = ScreenDims.Width - 15
        'Set MaxHeight by using reference control
        Dim MaxHeight As Integer = ScreenDims.Height - (RifCtrl.Location.Y + RifCtrl.Height + 40)

        Dim DGV_H As Integer = 0
        Dim DGV_W As Integer = 0
        'Set the DGV Width by using columns Width
        For Each C As DataGridViewColumn In DGV.Columns
            DGV_W += C.Width
        Next
        DGV.Width = DGV_W
        'Remove Horizontal ScrollBar by adding width
        Dim DGVHorizontalScroll As Control = DGV.Controls.OfType(Of HScrollBar).SingleOrDefault
        Do While DGVHorizontalScroll.Visible
            DGV.Width += 1
        Loop
        'Add 1 more pixel to width
        DGV.Width += 1
        'If is there a vertical ScrollBar then I get his width
        Dim VertSB_Width As Integer = 0
        Dim DGVVerticalScroll As Control = DGV.Controls.OfType(Of VScrollBar).SingleOrDefault
        If DGVVerticalScroll.Visible Then
            VertSB_Width = DGVVerticalScroll.Width
        End If
        'Set DGV Height by using Rows Height
        For Each R As DataGridViewRow In DGV.Rows
            DGV_H += R.Height
        Next
        'Add ColumnHeadersHeight to DGV Height
        DGV_H += DGV.ColumnHeadersHeight
        'If form size is enough to contain DGV I set his size
        'otherwise I set it to the max possible height
        If DGV_H <= MaxHeight Then
            DGV.Height = DGV_H
            'Try to remove Vertical ScrollBar
            Do While DGVVerticalScroll.Visible And DGV.Height <= MaxHeight
                DGV.Height += 1
            Loop
            adapted = Not DGVVerticalScroll.Visible
            'If VScroll was removed I need to resize Width
            If adapted AndAlso VertSB_Width > 0 Then
                DGV.Width -= (VertSB_Width) 
            End If
            'If DGV has onlu 1 row I need to add width
            '(I don't know why I need this!!!)
            If DGV.RowCount = 1 Then DGV.Width += 2
        Else
            DGV.Height = MaxHeight
            adapted = False
        End If
    Catch ex As Exception
        MsgBox(ex.ToString)
    End Try
    Return adapted
End Function

0 个答案:

没有答案