Reputation: 13592
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:
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.
Upvotes: 1
Views: 6408
Reputation: 3388
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;
}
}
}
}
Upvotes: 3