Click here to Skip to main content
15,903,854 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
Hi,
In my winform (4.0) I am using datagridview.
On hovering over the cells, the colour of the cell changes to yellow.
The DataGridViewCellStyle of the datagridview is set to : { BackColor=Color [A=255, R=244, G=244, B=244] }

The mouse goes over the cell which has an existing colour, then cell changes to yellow, BUT when the mouse moves away from the cell, the cell looses it's previous colour.
How can the cell have the same colour as before it turned yellow?
Thanks
C#
private void dgv_CellMouseEnter(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex > -1 && e.RowIndex > -1)
            {
                if (dgv[e.ColumnIndex, e.RowIndex].Value != null)
                {
                    if (dgv[e.ColumnIndex, e.RowIndex].Style.BackColor == Color.SkyBlue)
                    {
                        
                    }
                    else
                    {
                        dgv[e.ColumnIndex, e.RowIndex].Style.BackColor = Color.Gold;
                    }
                }
            }
        }

        private void dgv_CellMouseLeave(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex > -1 && e.RowIndex > -1)
            {
                if (dgv[e.ColumnIndex, e.RowIndex].Value != null)
                {
                    if (dgv[e.ColumnIndex, e.RowIndex].Style.BackColor == Color.SkyBlue)
                    {
                        
                    }
                    else
                    {
                        dgv[e.ColumnIndex, e.RowIndex].Style.BackColor = Color.White;
                    }
                }
            }
        }
Posted

1 solution

It looks like you are not saving the previous color of the cell before changing it.

Create a variable, say cellPrevColor, of type Color. In the CellMouseEnter event, save the back color before changing it. Then in the CellMouseLeave event, set the back color to the value of cellPrevColor.

Also, rather than using hard-coded colors, use the grid's color properties. Instead of changing the cell to Color.White, you probably want to use DefaultCellStyle.BackColor. That way, if you were to change the default cell style for whatever reason, you will not need to go back and rewrite blocks of code.
 
Share this answer
 
Comments
arkiboys 29-May-12 10:16am    
Thanks
Member 10651168 11-Apr-14 7:52am    
Thanks.
your answer too good

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900