【问题标题】:Allow DataGridView to grow and shrink height based on row data允许 DataGridView 根据行数据增长和缩小高度
【发布时间】:2014-06-12 14:20:12
【问题描述】:

我有一个 datagridview,我想根据里面的数据自动水平扩展和收缩,而不是让 datagrid 保持其静态高度并显示滚动条。

表单有一个一列三行的TableLayoutPanel;列和行设置为自动调整大小。 DataGridView 位于第二行(如图所示),并具有以下相关属性:

  • 锚点:左上角
  • AutoSizeColumnsMode:DisplayedCells
  • AutoSizeRowsMo​​de:无
  • 停靠:填充

每当行超过可视区域时,就会出现一个滚动条,但我希望 datagridview 与行一起增长。我怎样才能做到这一点?

注意:我们有适当的逻辑来确保表单永远不会超过用户监视器的大小。

【问题讨论】:

    标签: .net vb.net winforms


    【解决方案1】:

    我使用以下方法解决了这个问题,我将我的数据网格作为参数传递给(没有非代码解决方案来处理这种情况)。

    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
    

    【讨论】:

      【解决方案2】:

      我更喜欢订阅 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
      

      【讨论】:

        猜你喜欢
        • 2020-03-08
        • 2013-01-18
        • 1970-01-01
        • 2017-11-01
        • 1970-01-01
        • 1970-01-01
        • 2022-08-19
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多