我有一个datagridview,我希望根据里面的数据自动增长和收缩,而不是让datagrid保持静态高度并显示滚动条。
表单有一个TableLayoutPanel,有一列和三行;列和行设置为自动调整大小。 DataGridView位于第二行(如图所示),并具有以下相关属性:
每当行超过可视区域时,就会出现一个滚动条,但我希望datagridview随行一起增长。我怎么能做到这一点?
注意:我们有逻辑来确保表单永远不会超出用户监视器的大小。
答案 0 :(得分:1)
我通过以下方法解决了这个问题,我将datagrid作为参数传递给了(没有非代码解决方案来处理这种情况)。
Public Sub AdjustHeightOfGridBasedOnRows(ByVal dataGrid As DataGridView)
Dim totalRowHeight As Integer = dataGrid.ColumnHeadersHeight
For Each row As DataGridViewRow In dataGrid.Rows
totalRowHeight += row.Height
Next
dataGrid.Height = totalRowHeight
End Sub
答案 1 :(得分:0)
我更喜欢订阅DataGridView的RowsAdded和RowsRemoved事件。因此,无论何时行数发生变化,大小都会相应调整。
''' <summary>
''' Adujsts the height of a DataGridView when rows are added or removed.
''' </summary>
''' <param name="sender">This will be the DataGridView which will be modified</param>
''' <param name="e">The event args of from the addition or removal of a row</param>
''' <remarks>http://stackoverflow.com/questions/24186771/allow-datagridview-to-grow-and-shrink-height-based-on-row-data</remarks>
Private Sub DataGridView1_RowsAdded(sender As DataGridView, e As EventArgs) Handles DataGridView1.RowsAdded, DataGridView1.RowsRemoved
If sender.Rows.Count > 0 Then
Dim newHeight As Integer = 0
For Each row As DataGridViewRow In sender.Rows
newHeight += row.Height
Next
' Need to have this size doubled to give the buffer room for horizontal scroll bar.
' without it, if the horizontal scroll bar is displayed, then it will put in the
' vertical scroll bar for the last row. If the column headers are hidden, then
' add the height of the first row.
If sender.ColumnHeadersVisible Then
newHeight += sender.ColumnHeadersHeight * 2
Else
newHeight += sender.Rows(0).Height
End If
sender.Height = newHeight
End If
End Sub