How to set the back color of the row / column header cell in a datagridview - c# winform
I want to set the back color of the row header and column header intersection cell of a datagridview. I tried the below code, but it throws an exception that the number should be non negative.
DataGridViewCell cell = dgview.Rows[-1].Cells[-1];
cell.Style.BackColor = Color.Red;
I want to set the color as shown in the image below
I also refered the below article, but it shows how to set the color of the whole column header. But my requirement is to set the color of a single cell - row-column header intersection cell.
how-to-change-the-color-of-winform-datagridview-header
Any help is much appreciated. Thank you.
开发者_JS百科Regards,
Vinay
Store the current ColumnHeadersDefaultCellStyle in a variable.
Set the ColumnHeadersDefaultCellStyle to how you want the corner to be.
Then change all of the columns headers to how you want columns 0 to ... back to the old style.
Below is an example where the form is called "MyForm". This example shows the default constructor of MyForm.
Example:
public MyForm()
{
InitializeComponent();
// insert code here to add columns ...
// ...
// ...
// ...
DataGridViewCellStyle oldDefault = dgview.ColumnHeadersDefaultCellStyle.Clone();
dgview.ColumnHeadersDefaultCellStyle.BackColor = Color.Red;
foreach (DataGridViewColumn item in dgview.Columns)
{
item.HeaderCell.Style = oldDefault;
}
}
private void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
{
if (e.RowIndex == -1 && e.ColumnIndex == -1)
{
using (Brush gridBrush = new SolidBrush(this.dataGridView1.GridColor))
{
using (Brush backColorBrush = new SolidBrush(Color.Red))
{
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);
e.Handled = true;
}
}
}
}
This is a bit of a hack, but add a PictureBox inside the DataGridView using the designer(if you're using VS) and initialize it's properties such as:
pictureBox1.BackColor = Color.Red;
pictureBox1.Width = dgView.RowHeadersWidth;
pictureBox1.Height = dgView.ColumnHeadersHeight;
精彩评论