DataGridViewでヘッダーセルの結合を行う場合

DataGridViewでヘッダーセルの結合を行う場合、DataGridViewに既定で用意されている「CellPainting」イベントを使う。
以下は、2列目と3列目を結合して、「あああああああああああああああああ」と表示する場合の例です。

 private void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
        {
            // ガード句
            if (e.RowIndex > -1)
            {
                // ヘッダー以外は処理なし
                return;
            }

            //2〜3列目を結合する処理
            if (e.ColumnIndex == 1)
            {
                // 処理対象セルが、2列目の場合のみ処理を行う
                // セルの矩形を取得
                Rectangle rect = e.CellBounds;

                DataGridView dgv = (DataGridView)sender;

                // 3列目の幅を取得して、2列目の幅に足す
                rect.Width += dgv.Columns[2].Width;

                // 矩形の位置を補正
                rect.X -= 1;
                rect.Y -= 2;

                // 背景、枠線、セルの値を描画
                using (SolidBrush brush = new SolidBrush(dataGridView1.ColumnHeadersDefaultCellStyle.BackColor))
                {
                    // 背景の描画
                    e.Graphics.FillRectangle(brush,rect);
                    
                    using (Pen pen = new Pen(dgv.GridColor))
                    {
                        // 枠線の描画
                        e.Graphics.DrawRectangle(pen, rect);
                    }
                }

                // テキストの位置を調整
                rect.Y += 2;
                // セルに表示するテキストを描画
                TextRenderer.DrawText(e.Graphics,
                                "あああああああああああああああああ",
                                e.CellStyle.Font,
                                rect,
                                e.CellStyle.ForeColor,
                                TextFormatFlags.HorizontalCenter
                                | TextFormatFlags.VerticalCenter);
            }

            // 結合セル以外は既定の描画を行う
            if (!(e.ColumnIndex == 1 || e.ColumnIndex == 2))
            {
                e.Paint(e.ClipBounds, e.PaintParts);
            }

            // イベントハンドラ内で処理を行ったことを通知
            e.Handled = true;
        }