这是用于水平合并第一行的工作代码(包括居中单元格内容和正确绘制边框),初始代码可在
MSDN上找到:
private void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
{
if (e.RowIndex == 0)
{
if (e.ColumnIndex == 0)
{
e.PaintBackground(e.ClipBounds, true);
Rectangle r = e.CellBounds;
for (int i = 1; i < (sender as DataGridView).ColumnCount; i++)
r.Width += (sender as DataGridView).GetCellDisplayRectangle(i, 0, true).Width;
r.Width -= 1;
r.Height -= 1;
using (SolidBrush brBk = new SolidBrush(e.CellStyle.BackColor))
using (SolidBrush brFr = new SolidBrush(e.CellStyle.ForeColor))
{
e.Graphics.FillRectangle(brBk, r);
StringFormat sf = new StringFormat();
sf.Alignment = StringAlignment.Center;
sf.LineAlignment = StringAlignment.Center;
e.Graphics.TextRenderingHint = TextRenderingHint.AntiAliasGridFit;
e.Graphics.DrawString(e.Value.ToString(), e.CellStyle.Font, brFr, r, sf);
}
e.Handled = true;
}
else
if (e.ColumnIndex > 0)
{
using (Pen p = new Pen((sender as DataGridView).GridColor))
{
e.Graphics.DrawLine(p, e.CellBounds.Left, e.CellBounds.Bottom - 1, e.CellBounds.Right, e.CellBounds.Bottom - 1);
if (e.ColumnIndex == (sender as DataGridView).ColumnCount - 1)
e.Graphics.DrawLine(p, e.CellBounds.Right - 1, e.CellBounds.Top, e.CellBounds.Right - 1, e.CellBounds.Bottom);
}
e.Handled = true;
}
}
}
private void dataGridView1_Scroll(object sender, ScrollEventArgs e)
{
for (int i = 0; i < (sender as DataGridView).ColumnCount; i++)
(sender as DataGridView).InvalidateCell(i, 0);
}
dataGridView1_CellPainting
事件中设置e.AdvancedBorderStyle.Right = DataGridViewAdvancedCellBorderStyle.None
?这对于水平合并来说不太适用,因为第一列(如果我将工作时间字符串放入行的第一个单元格中)将根据其长度自动调整大小。它看起来不像是合并的列,而是像这样的东西。 - bairogCellPainting
事件来居中内容)。但是我无法回答自己的问题,因为您已经关闭了它。请打开它 - 这样我就能添加完整和正确的解决方案。谢谢。 - bairog