Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find out which DataGridView rows are currently onscreen?

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?

like image 619
Seidleroni Avatar asked May 18 '11 13:05

Seidleroni


People also ask

How do I make the DataGridView show the selected row?

Just set the CurrentCell property, the DGV will scroll to make it visible.

How can I tell if a DataGridView has changed?

If you populate the DataGridView with a DataSet table you can use the . GetChanges method to find out which rows, if any, have changed.

What is DataGridViewRow?

The DataGridViewRow class represents a row in a DataGridView control. You can retrieve rows through the Rows and SelectedRows collections of the control. Unlike a DataGridViewColumn, a DataGridViewRow physically contains a collection of all of the cells in that row.


2 Answers

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.

like image 68
Alireza Maddah Avatar answered Sep 28 '22 07:09

Alireza Maddah


    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

like image 38
Pierpaolo Simoncini Avatar answered Sep 28 '22 05:09

Pierpaolo Simoncini