如何找出哪些DataGridView行当前在屏幕上?

问题描述:

在我的C#(2010)应用程序,我有一个DataGridView在虚拟模式下,它拥有几千行。目前是否可以找出屏幕上有哪些单元格?如何找出哪些DataGridView行当前在屏幕上?

public void GetVisibleCells(DataGridView dgv) 
    { 
     var vivibleRowsCount = dgv.DisplayedRowCount(true); 
     var firstDisplayedRowIndex = dgv.FirstDisplayedCell.RowIndex; 
     var lastvibileRowIndex = (firstDisplayedRowIndex + vivibleRowsCount) - 1; 
     for (int rowIndex = firstDisplayedRowIndex; rowIndex <= lastvibileRowIndex; rowIndex++) 
     { 
      var cells = dgv.Rows[rowIndex].Cells; 
      foreach (DataGridViewCell cell in cells) 
      { 
       if (cell.Displayed) 
       { 
        // This cell is visible... 
        // Your code goes here... 
       } 
      } 
     } 
    } 

更新:它现在找到可见的单元格。

+0

这正是我所需要的!谢谢。 – Seidleroni 2011-05-18 15:35:10

+2

ATTN:如果网格中有不可见的行,则不能计算lastvibileRowIndex。在这种情况下,你必须在for循环中检查行的Visible属性,并对这些可见行进行计数,直到达到vivibleRowsCount。 – 2014-07-07 12:48:41

我还没有尝试过这个自己,但在我看来,在确定使用DataGridView.GetRowDisplayRectangle行的矩形,并检查它是否重叠当前DataGridView.DisplayRectangle将要走的路。 Rectangle.IntersectsWith对此很有用。

作为一个优化,我会使用DataGridView .DisplayedRowCount找到第一个可见行后确定哪些行是可见的。