Grid View合并单元格
Windows Forms DataGridView 没有提供合并单元格的功能,要实现合并单元格的功能就要在CellPainting事件中使用Graphics.DrawLine和 Graphics.DrawString 自己来“画”。
如下合并第一列,有相同邻居相同值的单元格
private void dgviewGKSY_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
{
// 对第1列相同单元格进行合并
if (e.ColumnIndex == 0 && e.RowIndex != -1)
{
//每列高度
double eachHeight = dgviewGKSY.Height / dgviewGKSY.Rows.Count;
using
(
Brush gridBrush = new SolidBrush(this.dgviewGKSY.GridColor),
backColorBrush = new SolidBrush(e.CellStyle.BackColor)
)
{
using (Pen gridLinePen = new Pen(gridBrush))
{
// 清除单元格
e.Graphics.FillRectangle(backColorBrush, e.CellBounds);
// 画 Grid 边线(仅画单元格的底边线和右边线)
//最后一行画底边线
if (e.RowIndex == dgviewGKSY.Rows.Count - 1)
{
e.Graphics.DrawLine(gridLinePen, e.CellBounds.Left,
e.CellBounds.Bottom - 1, e.CellBounds.Right - 1,
e.CellBounds.Bottom - 1);
}
// 画右边线,所有行都得画右边线啦
e.Graphics.DrawLine(gridLinePen, e.CellBounds.Right - 1,
e.CellBounds.Top, e.CellBounds.Right - 1,
e.CellBounds.Bottom);
// 如果下一行和当前行的数据不同,则在当前的单元格画一条底边线,表示没得合并了
if (e.RowIndex < dgviewGKSY.Rows.Count - 1 &&
dgviewGKSY.Rows[e.RowIndex + 1].Cells[e.ColumnIndex].Value.ToString() !=
e.Value.ToString())
e.Graphics.DrawLine(gridLinePen, e.CellBounds.Left,
e.CellBounds.Bottom - 1, e.CellBounds.Right - 1,
e.CellBounds.Bottom - 1);
// 画(填写)单元格内容,相同的内容的单元格只填写第一个
if (e.Value != null)
{
//当该行和下一行的内容相同时就不画,就是说等到该值的最后一个才画
if (e.RowIndex > -1 && e.RowIndex
e.Value.ToString())
{
equalCount++;
}
else
{
//量出字符的测量值,包括宽度高度
SizeF strSize = e.Graphics.MeasureString(dgviewGKSY.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString(), this.dgviewGKSY.Font);
//计算一个中间的列,然后在相应位置画出来
//合并高度
double allHeight = equalCount * eachHeight;
//中间位置
double midHeight = allHeight / 2;
int yloc = e.CellBounds.Y - Convert.ToInt32(midHeight);
int yLoc = Convert.ToInt32(yloc+ strSize.Height / 2);
int xLoc = Convert.ToInt32(e.CellBounds.X + (e.CellBounds.Width - strSize.Width) / 2);
e.Graphics.DrawString(dgviewGKSY.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString(), e.CellStyle.Font,
Brushes.Black, xLoc,
yLoc, StringFormat.GenericDefault);
equalCount = 0;
}
}
e.Handled = true;
}
}
}
}
不过此时会有问题:第一次显示是很好的,但当点击了合并单元格时就会出现很怪的事情,字符乱显示在某个位置了,怎么解决?