I only want the background color of certain row headers to change without losing the cool default windows styles that come with DataGridView:
Grid.EnableHeadersVisualStyles = false;
for(int i=0; i<Grid.Rows.Count; i++)
{
if ( /*I want to change this row */)
{
DataGridViewCellStyle rowStyle = Grid.RowHeadersDefaultCellStyle;
rowStyle.BackColor = Color.Wheat;
Grid.Rows[i].HeaderCell.Style = rowStyle;
}
}
As soon as I do this I lose the MouseOver blue effect on the columns, and the sort arrow on the columns is grayed. I have tried to set the column headers to the defaultColHeaderStyle to no avail. The row header changes to the desired color, its the column headers lose their slick Windows style. Any help?
The default style for the row header should already be defined when you build your DataGridView
. So I would use:
if ( /*I want to change this row */)
{
DataGridViewCellStyle rowStyle; // = Grid.RowHeadersDefaultCellStyle;
rowStyle = Grid.Rows[i].HeaderCell.Style;
rowStyle.BackColor = Color.Wheat;
Grid.Rows[i].HeaderCell.Style = rowStyle;
}
This way you fill your rowStyle
with the predefined style and then change only the part you want to change. See if this solves your problem.
//EDIT As you wish to keep the other stylings of the default Windows DataGridView, you would also need to set more of the other parameters of the style. See this post.
Or try this. When initialiazing:
dataGridView1.CellPainting +=
new DataGridViewCellPaintingEventHandler (dataGridView_CellPainting);
Then create the handler function with something like:
void dataGridView_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
{
DataGridView dv = sender as DataGridView;
DataGridViewCellStyle rowStyle;// = dv.RowHeadersDefaultCellStyle;
if (e.ColumnIndex == -1)
{
e.PaintBackground(e.CellBounds, true);
e.Handled = true;
if (/*I want to change this row */)
{
rowStyle = dv.Rows[e.RowIndex].HeaderCell.Style;
rowStyle.BackColor = Color.Wheat;
dv.Rows[e.RowIndex].HeaderCell.Style = rowStyle;
using (Brush gridBrush = new SolidBrush(Color.Wheat))
{
using (Brush backColorBrush = new SolidBrush(e.CellStyle.BackColor))
{
using (Pen gridLinePen = new Pen(gridBrush))
{
// Clear cell
e.Graphics.FillRectangle(backColorBrush, e.CellBounds);
//Bottom line drawing
e.Graphics.DrawLine(gridLinePen, e.CellBounds.Left, e.CellBounds.Bottom - 1, e.CellBounds.Right, e.CellBounds.Bottom - 1);
// here you force paint of content
e.PaintContent(e.ClipBounds);
e.Handled = true;
}
}
}
}
}
}
This code was based on this post. You would only then need to create more paint conditions for mouseover and selected state. But this should work for you.
Remember to remove: Grid.EnableHeadersVisualStyles = false;
or force it to: Grid.EnableHeadersVisualStyles = true;
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With