C#控件:DataGridView合并单元格

来源:互联网 发布:简述js闭包使用场景 编辑:程序博客网 时间:2024/05/17 03:36

  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

0 0
原创粉丝点击