35

How do I change the datagridview selected row background color in C# windows applications?

1
  • You need to add more detail to the question, perhaps post some code and what you have tried and what failed. Your question as it stands is not answerable.
    – Oded
    Jul 5, 2010 at 9:32

6 Answers 6

55

Come on man... there has to be a simple solution, and finally got one.

dataGridView1.DefaultCellStyle.SelectionBackColor = Color.Blue;
dataGridView1.DefaultCellStyle.SelectionForeColor = Color.Red;

This worked for me, no complex codes, no event handling. I did it before but was not able to recall so thought posting it would help others and me in future :)

0
34

On the DataGridView there is a DefaultCellStyle, inside this there is SelectionBackColor and SelectionForeColor properties.

The DataGridView uses a style inheritance idea, in case you find that the style you pick is not being applied:

http://msdn.microsoft.com/en-us/library/1yef90x0.aspx

4

This is the simple and working version that you can copy and paste:

private void dataGridView1_SelectionChanged(object sender, EventArgs e)
{
    (sender as DataGridView).CurrentRow.DefaultCellStyle.SelectionBackColor = Color.Green;
}
1
  • this is what i really looking for, thanks!
    – Freddy
    May 7, 2021 at 14:02
3

Taking advantage of DataGridViewCell's events CellEnter and CellLeave you might try something like this:

private void foobarDataGridView_CellEnter(object sender, DataGridViewCellEventArgs e)
{
  DataGridViewCellStyle fooCellStyle = new DataGridViewCellStyle();
  fooCellStyle.BackColor = System.Drawing.Color.LightYellow;
  this.VariableFinderDataGridView.CurrentCell.Style.ApplyStyle(fooCellStyle);
}

private void foobarFinderDataGridView_CellLeave(object sender, DataGridViewCellEventArgs e)
{
  DataGridViewCellStyle barCellStyle = new DataGridViewCellStyle();
  barCellStyle.BackColor = System.Drawing.Color.White;
  this.VariableFinderDataGridView.CurrentCell.Style.ApplyStyle(barCellStyle);
}
2
  • What if the row color before selection was not white?
    – Thunder
    May 25, 2012 at 11:29
  • I mean that was just a quick sample to illustrate the concept -- you just create a helper method to retrieve whatever color you need to toggle there. May 26, 2012 at 17:48
3

The color can be changed also in the designer of a 'DataGridView'

enter image description here

2

Here is my code

private void dataGridView1_CellContentClick_1(object sender, DataGridViewCellEventArgs e)
{
dataGridView1.CurrentRow.DefaultCellStyle.BackColor = Color.Maroon;
dataGridView1.CurrentRow.DefaultCellStyle.ForeColor = Color.White;
}
1
  • Nice one Adam! I never knew that existed!!
    – user7075507
    Dec 2, 2016 at 0:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.