How to find out which DataGridView rows are currently onscreen?

Seidleroni picture Seidleroni · May 18, 2011 · Viewed 22.4k times · Source

In my C# (2010) application I have a DataGridView in Virtual Mode which holds several thousand rows. Is it possible to find out which cells are onscreen at the moment?

Answer

Alireza Maddah picture Alireza Maddah · May 18, 2011
public void GetVisibleCells(DataGridView dgv)
    {
        var visibleRowsCount = dgv.DisplayedRowCount(true);
        var firstDisplayedRowIndex = dgv.FirstDisplayedCell.RowIndex;
        var lastvisibleRowIndex = (firstDisplayedRowIndex + visibleRowsCount) - 1;
        for (int rowIndex = firstDisplayedRowIndex; rowIndex <= lastvisibleRowIndex; rowIndex++)
        {
            var cells = dgv.Rows[rowIndex].Cells;
            foreach (DataGridViewCell cell in cells)
            {
                if (cell.Displayed)
                {
                    // This cell is visible...
                    // Your code goes here...
                }
            }
        }
    }

Updated: It now finds visible cells.