DataGridView - Change selection color when focus lost

  • Thread starter Thread starter Steve K
  • Start date Start date
S

Steve K

(I had posted this in the C# group and then found this group which I think is more appropriate)

I realized tonight that the DataGridView doesn't support a different selection color when it doesn't have focus. After
realizing this I set out on what I thought would be a quick and simple task to solve the problem.

Granted I'm no DataGridView expert, but to me this seems like it should work and it's not. I've tried adding explicit
calls to Invalidate() and it makes no different.

The code below is attempting to set the selection background color to Red when blurred and Blue when focused. These are
of course just testing colors.

I would really appreciate any tips any of you may have.

Note: I left the commented code in place so that you can see the original approach that I took before reducing this to a
dead-simple test.



Code:
using System;
using System.Drawing;
using System.Windows.Forms;

namespace PMD.Library.WinFormControls
{
public class PMDDataGridView : DataGridView
{
//        private Color _blurredSelectionBackGround = Color.Red;

protected override void OnGotFocus(EventArgs e)
{
Console.WriteLine("OnGotFocus called");
this.DefaultCellStyle.SelectionBackColor = Color.Blue;

/*
if (this.CurrentCell != null)
{
if (this.SelectionMode == DataGridViewSelectionMode.FullRowSelect)
{

this.Rows[this.CurrentCell.RowIndex].DefaultCellStyle.SelectionBackColor =
this.DefaultCellStyle.SelectionBackColor;
}
else
{
this.CurrentCell.Style.SelectionBackColor =
this.DefaultCellStyle.SelectionBackColor;
}
}
*/

base.OnGotFocus(e);
}

protected override void OnLostFocus(EventArgs e)
{
Console.WriteLine("OnLostFocus called");
this.DefaultCellStyle.SelectionBackColor = Color.Red;

/*
if (this.CurrentCell != null)
{
if (this.SelectionMode == DataGridViewSelectionMode.FullRowSelect)
{

this.Rows[this.CurrentCell.RowIndex].DefaultCellStyle.BackColor =
this._blurredSelectionBackGround;
}
else
{
this.CurrentCell.Style.SelectionBackColor = this._blurredSelectionBackGround;
}
}
*/

base.OnLostFocus(e);
}
}
}
 
Back
Top