C#控件:DataGridView合并单元格

  private void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
        {
            if (e.ColumnIndex == 2 && e.RowIndex != -1 || e.ColumnIndex == 3 && e.RowIndex != -1 || e.ColumnIndex == 4 && e.RowIndex != -1)
            {
                Brush bruch = new SolidBrush(dataGridView1.GridColor);
                SolidBrush sbruch = new SolidBrush(e.CellStyle.BackColor);
                using(Pen pen = new Pen(bruch))
                {
                    e.Graphics.FillRectangle(sbruch,e.CellBounds);
                    if (e.RowIndex < dataGridView1.Rows.Count - 1 && dataGridView1.Rows[e.RowIndex + 1].Cells[e.ColumnIndex].Value != null && dataGridView1.Rows[e.RowIndex + 1].Cells[e.ColumnIndex].Value.ToString() != e.Value.ToString())
                    {
                        e.Graphics.DrawLine(pen, e.CellBounds.Left, e.CellBounds.Bottom - 1, e.CellBounds.Right, e.CellBounds.Bottom - 1);
                        e.Graphics.DrawLine(pen, e.CellBounds.Right - 1, e.CellBounds.Top, e.CellBounds.Right - 1, e.CellBounds.Bottom);
                    }
                    else
                    {
                        e.Graphics.DrawLine(pen, e.CellBounds.Right - 1, e.CellBounds.Top, e.CellBounds.Right - 1, e.CellBounds.Bottom);
                    }
                    if (e.RowIndex == dataGridView1.Rows.Count - 1)
                    {
                        e.Graphics.DrawLine(pen, e.CellBounds.Left, e.CellBounds.Bottom - 1, e.CellBounds.Right, e.CellBounds.Bottom - 1);
                    }
                    if (e.Value != null)
                    {
                        if (!(e.RowIndex > 0 && dataGridView1.Rows[e.RowIndex - 1].Cells[e.ColumnIndex].Value.ToString() == e.Value.ToString()))
                        {
                            e.Graphics.DrawString(e.Value.ToString(),e.CellStyle.Font,Brushes.Black,e.CellBounds.X+2,e.CellBounds.Y+5,StringFormat.GenericDefault);
                        }
                    }
                    e.Handled = true;                }
            }
        }

 

转载来自:http://wangyi-1984.diandian.com/post/2012-02-15/40030786188

你可能感兴趣的:(合并,单元格)