C# – DataGridView doesn’t call Paint method when InvalidateCell is called

c++datagridviewwinforms

This a WinForm C# application problem.

I have a DataGridView and I need a customized type of DataGridViewColumn such that when my mouse is over a cell on that column, the cell paints something special on it. I found a way of overriding the DataGridViewTextBoxCell to do the painting myself. That article shows an example of implementing a roll-over cell such that when you move your mouse over a cell, it paints a red rectangle around the bounders of itself.

If you see the example, you will find out that the way the example fills data is directly create rows to the grid. When I use data binding rather than direct row fill, I find that the cells will not paint themselves at the beginning. Actually, you have to select a cell first, then all the cells on that row will paint correctly. If you don't select a cell of a row, all the cells on that row will not paint accordingly when the mouse is over them.

I think this is some kind of optimization of the grid such that when you select a cell, the underlying object of that row is activated and the grid will call Paint method when InvlidateCell method is call. But if the underlying object of a row is not activated, the grid will just paint the cells by default method to save time.

Obviously, I need not the optimization but the slow way. It doesn't matter in my case because my data on that grid never get too big. How can I achieve it? I try to call grid.Refresh() after the data is bound to the grid but that doesn't help.

Thank you for your suggestion.

Ji

Best Solution

Not totally sure I understood your question. Just see if this is somewhat like what you need:

bool bSomeFlag = false;
int iCol = 0;
int iRow = 0;
private void dataGridView1_CellMouseMove(object sender, DataGridViewCellMouseEventArgs e) {
            iCol = e.ColumnIndex;
            iRow = e.RowIndex;
            bSomeFlag = true;
            this.dataGridView1.Invalidate();
        }
private void dataGridView1_Paint(object sender, PaintEventArgs e) {
            if (bSomeFlag && iRow >=0 && iCol>=0) {
                dataGridView1.Rows[iRow].Cells[iCol].Style.BackColor = Color.Red;
            }
        }