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?
Asked
Active
Viewed 2.4k times
3 Answers
35
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.

Beetee
- 475
- 1
- 7
- 18

Alireza Maddah
- 5,718
- 2
- 21
- 25
-
2ATTN: You cannot calculate lastvibileRowIndex like that if you are having invisible rows in the grid. In such case you have to check Visible property of row in for-loop and count those visible rows until you reach vivibleRowsCount. – Sir Kill A Lot Jul 07 '14 at 12:48
1
private bool RowIsVisible(DataGridViewRow row)
{
DataGridView dgv = row.DataGridView;
int firstVisibleRowIndex = dgv.FirstDisplayedCell.RowIndex;
int lastVisibleRowIndex = firstVisibleRowIndex + dgv.DisplayedRowCount(false) - 1;
return row.Index >= firstVisibleRowIndex && row.Index <= lastVisibleRowIndex;
}
IMHO Regards

Pierpaolo Simoncini
- 11
- 1
-
Welcome to SO. Please explain how it adds anything to the accepted answer from 2011, and how it addresses the comment made to it in 2014 about invisible rows. – AntoineL Feb 18 '20 at 09:47
1
I haven't tried this myself, but it seems to me that determining the rectangle of a row using DataGridView.GetRowDisplayRectangle and checking if it overlaps the current DataGridView.DisplayRectangle would be the way to go. Rectangle.IntersectsWith is useful in to do this.
As an optimization I would use DataGridView .DisplayedRowCount after finding the first visible row to determine what rows are visible.

larsmoa
- 12,604
- 8
- 62
- 85