Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I change the datagridview selected row background color?

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

like image 302
Lawrance Rozario Avatar asked Jul 05 '10 09:07

Lawrance Rozario


4 Answers

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 :)

like image 90
Bravo Avatar answered Oct 20 '22 21:10

Bravo


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

like image 38
Adam Houldsworth Avatar answered Oct 20 '22 21:10

Adam Houldsworth


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);
}
like image 27
Nano Taboada Avatar answered Oct 20 '22 22:10

Nano Taboada


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;
}
like image 3
AecorSoft Avatar answered Oct 20 '22 22:10

AecorSoft