Q:

synchronize drawing of rectangles and scrolling in datagridview

I am currently working on the cell selection function for a datagridview, I draw rectangles around the cells to simulate the selection, using co-ordinates and size for the rectangle. The problem arises when I scroll down or right to select more cells. While selecting, the rectangles are drawn with the same dimensions and parameters irrespective of which cells are bounded by the rectangle. 
I would like to know how do I synchronize my rectangle drawings with the scrolling so as to keep the same cells selected/bounded in the rectangle.
Any help or direction towards this is appreciated.
Thanks

A:

I don't know what technique you're currently using, but it's worth saying that painting directly onto the DataGridView control by handling its Paint event is ill-advised.
You will have to break up your painting code into the bounds of specific cells and/or rows and paint in the CellPainting or 'RowPostPaint` events. To draw a rectangle around several cells, you could either paint inside the borders of the affected cells, or paint in the adjacent cells.
The CellBounds property of DataGridViewCellPaintingEventArgs gives you coordinates that are always relative to the cell itself, which means that it will adapt automatically to scrolling within the DataGridView.
Edit: An example of how to handle the CellPainting event to draw a custom border around a specific cell:
void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e) {
    e.Paint(e.ClipBounds, e.PaintParts);
    if ((e.RowIndex == myRowIndex) && (e.ColumnIndex == myColumnIndex)) {
        Pen pen = new Pen(Color.Red, 2f);
        e.Graphics.DrawRectangle(pen, e.CellBounds);
    }
    e.Handled = true;
}

