如何在DataGridView中设置特定标题单元格的边框颜色
本文关键字:单元格 标题 边框 颜色 DataGridView 设置 | 更新日期: 2023-09-27 17:54:20
谁能帮我解决如何在C#
winform中设置DataGridView
中特定标题单元格的边框颜色的问题?
我在C#
winform中有一个DataGridView
,我的要求是,当我们点击标题单元格时,我想设置标题单元格的边框颜色。
没有直接的方法。您必须在CellPainting
事件处理程序中绘制自己的边界。
使用类级别变量来存储已单击的列标头索引。
int myClickedColumnHeaderIndex = -1;
订阅以下活动。
dataGridView1.CellPainting += dataGridView1_CellPainting;
dataGridView1.ColumnHeaderMouseClick += new DataGridViewCellMouseEventHandler(dataGridView1_ColumnHeaderMouseClick);
在ColumnHeaderMouseClick
处理程序中使用类级别变量存储列索引。
void dataGridView1_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
if (e.Button == MouseButtons.Left && e.Clicks == 1)
{
dataGridView1.InvalidateCell(myClickedColumnHeaderIndex, -1); // this to trigger paint of the old cell inorder to remove the border drawn earlier.
myClickedColumnHeaderIndex = e.ColumnIndex;
}
}
在CellPainting
事件处理程序中,使用所需的颜色绘制边框。
void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
{
if (e.RowIndex == -1 && e.ColumnIndex >= 0 && e.ColumnIndex == myClickedColumnHeaderIndex)
{
e.Paint(e.CellBounds, DataGridViewPaintParts.All & ~DataGridViewPaintParts.Border);
using (Pen customPen = new Pen(Color.Blue, 2))
{
Rectangle rect = e.CellBounds;
rect.Width -= 2;
rect.Height -= 2;
e.Graphics.DrawRectangle(customPen, rect);
}
e.Handled = true;
}
}
此代码为标题单元格和每个偶数列的数据单元格绘制垂直边框。
private void DgvCalendar_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
{
int columnIndex = 0;
if (e.RowIndex >= 0 && e.ColumnIndex >= columnIndex)
{
if (e.ColumnIndex % 2 == 0)
{
var brush = new SolidBrush(dgvCalendar.ColumnHeadersDefaultCellStyle.BackColor);
e.Graphics.FillRectangle(brush, e.CellBounds);
brush.Dispose();
e.Paint(e.CellBounds, DataGridViewPaintParts.All & ~DataGridViewPaintParts.ContentBackground);
ControlPaint.DrawBorder(e.Graphics, e.CellBounds,
System.Drawing.Color.Transparent, 1, ButtonBorderStyle.Solid,
System.Drawing.Color.Transparent, 1, ButtonBorderStyle.Solid,
System.Drawing.Color.CornflowerBlue, 1, ButtonBorderStyle.Solid,
System.Drawing.Color.Transparent, 1, ButtonBorderStyle.Solid);
e.Handled = true;
}
}
if (e.RowIndex == -1 && e.ColumnIndex >= columnIndex)
{
if (e.ColumnIndex % 2 == 0)
{
e.Paint(e.CellBounds, DataGridViewPaintParts.All & ~DataGridViewPaintParts.Border);
ControlPaint.DrawBorder(e.Graphics, e.CellBounds,
System.Drawing.Color.Transparent, 1, ButtonBorderStyle.Solid,
System.Drawing.Color.Transparent, 1, ButtonBorderStyle.Solid,
System.Drawing.Color.CornflowerBlue, 1, ButtonBorderStyle.Solid,
System.Drawing.Color.Transparent, 1, ButtonBorderStyle.Solid);
e.Handled = true;
e.Handled = true;
}
}
}