1
votes

I am working on a custom DataGridView derived from System.Windows.Forms.DataGridView.

In my desired grid my rows may have different colors due to their state, and I want the current row to be a little different from Other rows, and that difference is in color being highlighted which is dynamic rather than being static.

When I select a row, I simply want to keep the previous color of the row, then highligh that color relatively, which I have done whit this code snippet:

Color oldColor;
private void dgvMain_SelectionChanged(object sender, EventArgs e)
{
    oldColor = dgvMain.CurrentRow.DefaultCellStyle.BackColor;
    Color newColor = Color.FromArgb(oldColor.R  < 235 ? oldColor.R + 20 : 0,
                                    oldColor.G, oldColor.B);
    dgvMain.CurrentRow.DefaultCellStyle.BackColor = newColor;
}

but I have 2 problems:

  1. When I select a row, first my code changes the row's color, then the row gets selected so its color changes to the default selection color.
  2. When the row loses its selection (is deselcted) I can not recover it's old color - I have the oldColor but I don't know when CurrentRow is changed, I know that some rows have had changes in their selection state, but I don't know exactly which row was my previous row to change its color.

Is there any workaround to do this? Any event or special code?


And also if you know a better solution for highlighting colors, I'll appreciate your help.

1

1 Answers

3
votes

There is a separate property SelectionBackColor in DefaultCellStyle. Use this to change the selection color. You can have the default cell style stored and use this for restoring the default values.

Sample Code:

public class BetterDataGridView : DataGridView
{
    private DataGridViewCellStyle defaultStyle = new DataGridViewCellStyle();
    public BetterDataGridView()
    {

    }

    protected override void OnRowStateChanged(int rowIndex, DataGridViewRowStateChangedEventArgs e)
    {
        base.OnRowStateChanged(rowIndex, e);
        if (rowIndex > -1)
        {
            DataGridViewRow row = this.Rows[rowIndex];
            if (row.Selected)
            {
                Color oldColor = this.CurrentRow.DefaultCellStyle.SelectionBackColor;
                e.Row.DefaultCellStyle.SelectionBackColor = Color.FromArgb(oldColor.R < 235 ? oldColor.R + 20 : 0,
                                    oldColor.G, oldColor.B);
            }
            else if (!row.Selected)
            {
                e.Row.DefaultCellStyle.SelectionBackColor = defaultStyle.SelectionBackColor;
            }
        }
    }
}