■■■

2016年4月6日水曜日

DataGridViewで任意のセルを結合する方法

DataGridViewで任意のセルを結合する方法
DataGridViewではセル結合機能はありませんので、高額なサードパティ製品を利用することがお勧めになってきます。
しかし、コストをかけずに結合しているように見えればいいというのであれば以下のような方法があります。
DataGridViewのPaintイベントでセルを描画するという方法です。

下記を実行するとDataGridView上に四角形が描かれます。これをセルにぴったりと合わせることで疑似的に結合させることが可能になります。


VB.NET


Private Sub dgv1_Paint1(ByVal sender As Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles dgv1.Paint

e.Graphics.FillRectangle(Brushes.Red, 1, 1, 50, 50)

End Sub


C#


private void dgv1_Paint1(object sender, System.Windows.Forms.PaintEventArgs e)
{
e.Graphics.FillRectangle(Brushes.Red, 1, 1, 50, 50);

}



セルに合わせて四角形を描画する方法


VB.NET

Private Sub dgv1_Paint1(ByVal sender As Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles dgv1.Paint

Dim bCell as Brush = Brushes.Red
Dim bFont As Brush = Brushes.Blue
Dim sFmt As New StringFormat
Dim dRct As Rectangle = New Rectangle(1, 1, 100, 100)
Dim dFont = New Font("MS UI Gothic", 9.0F, FontStyle.Regular, GraphicsUnit.Point)

'セル描画
e.Graphics.FillRectangle(bCell , dRct) 
'文字
e.Graphics.DrawString("test", dFont , bFont , dRct, sFmt) 

End Sub



C#

private void dgv1_Paint1(object sender, System.Windows.Forms.PaintEventArgs e)
{
Brush bCell = Brushes.Red; Brush bFont = Brushes.Blue; StringFormat sFmt = new StringFormat(); Rectangle dRct = new Rectangle(1, 1, 100, 100); dynamic dFont = new Font("MS UI Gothic", 9f, FontStyle.Regular, GraphicsUnit.Point); //セル描画 e.Graphics.FillRectangle(bCell, dRct); //文字 e.Graphics.DrawString("test", dFont, bFont, dRct, sFmt);

}






■■■