如何在DataGridView中设置特定标题单元格的边框颜色 [英] How to set the border color of a particular header cell in DataGridView
问题描述
有谁能帮助我解决如何在 C#中的
DataGridView
中设置特定标题单元格的边框颜色的问题? / code> winform。
Can any one help me to resolve the issue of how to set the border color of a particular header cell in a DataGridView
in a C#
winform.
我在 C#中有一个
winform,我的要求是我想在单击标题单元格时设置标题单元格的边框颜色。 DataGridView
I have a DataGridView
in C#
winform and my requirement is that I want to set the border color of header cell when we click on header cell.
推荐答案
没有直接的方法可以做到这一点。您必须在 CellPainting
事件处理程序中绘制自己的边框。
There is no direct way of doing this. You have to draw your own border in CellPainting
event handler.
具有一个类级变量来存储单击的列
Have a class level variable to store the clicked column header index.
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中
事件处理程序,使用所需的颜色绘制边框。
In the CellPainting
event handler, draw the border using the required color.
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;
}
}
这篇关于如何在DataGridView中设置特定标题单元格的边框颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!