c# - 如何将具有水平合并单元格的行添加到 DataGridView
解决方案
这是第一行水平合并的工作代码(用于居中单元格内容和正确的边框绘制),初始代码在 MSDN 上找到:
private void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
{
//mering all cells in a first row
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))
{
//bottom line of a cell
e.Graphics.DrawLine(p, e.CellBounds.Left, e.CellBounds.Bottom - 1, e.CellBounds.Right, e.CellBounds.Bottom - 1);
//right vertical line of a last cell in a row
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)
{
//force redraw first row when scrolling
for (int i = 0; i < (sender as DataGridView).ColumnCount; i++)
(sender as DataGridView).InvalidateCell(i, 0);
}
推荐阅读
- java - 如何将击键发送到非活动窗口?
- python - Python:使用上述单元格中的公式自动填充单元格,MAC OS
- java - 如何了解 Android Studio Bundle 中的“关键”是什么?
- cplex - 预求解阶段的 Cplex 限制时间
- php - HTML 数据源 PHP 脚本返回未捕获的错误
- r - 在 R 中创建流程图
- python - 从我的数据框中计算加权平均值
- html - 需要仅使用 CSS 下推 div
- python - 如何附加到具有前 5 个分数和相应用户的外部文件
- javascript - 在 div 而不是 input/textarea 中时无法通过 POST 发送内容