[英]How to set the border color of a particular header cell in DataGridView
任何人都可以幫我解決如何在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;
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.