如何在DataGridView中添加一个包含水平合并单元格的行

3
我正在使用WinForms。 如何向DataGridView添加具有水平合并单元格的行? 类似于以下图片中的工作时间着陆计数单元格:

enter image description here

最初的回答:

请查看此线程,它几乎回答了你的问题 https://dev59.com/EmQn5IYBdhLWcg3wg3aR - Max Shevchenko
1
我看到你建议我在dataGridView1_CellPainting事件中设置e.AdvancedBorderStyle.Right = DataGridViewAdvancedCellBorderStyle.None?这对于水平合并来说不太适用,因为第一列(如果我将工作时间字符串放入行的第一个单元格中)将根据其长度自动调整大小。它看起来不像是合并的列,而是像这样的东西。 - bairog
这个并没有得到很好的支持。解决方法是可以隐藏一些边框,但是除非你绘制所有者,否则内容将不会居中。点击此处查看 - TaW
@TaW - 我已经编写了一些代码,对我来说很有效(不仅限于边框,还使用自定义的CellPainting事件来居中内容)。但是我无法回答自己的问题,因为您已经关闭了它。请打开它 - 这样我就能添加完整和正确的解决方案。谢谢。 - bairog
1个回答

1
这是用于水平合并第一行的工作代码(包括居中单元格内容和正确绘制边框),初始代码可在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);
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接