■■■

2016年4月1日金曜日

DataGridViewのヘッダー部に行番号を付ける方法

DataGridViewのヘッダー部に行番号を付ける方法
VB.NET
Private Sub dgv1_CellPainting(ByVal sender As Object, _
ByVal e As DataGridViewCellPaintingEventArgs) _
Handles dgv1.CellPainting
If e.ColumnIndex < 0 And e.RowIndex >= 0 Then
e.Paint(e.ClipBounds, DataGridViewPaintParts.All)
Dim indexRect As Rectangle = e.CellBounds
indexRect.Inflate(-2, -2)
TextRenderer.DrawText(e.Graphics, _
(e.RowIndex + 1).ToString(), _
e.CellStyle.Font, _
indexRect, _
e.CellStyle.ForeColor, _
TextFormatFlags.Right Or TextFormatFlags.VerticalCenter)
e.Handled = True
End If
End Sub
C#
private void dgv1_CellPainting(object sender,
DataGridViewCellPaintingEventArgs e)
{
if (e.ColumnIndex < 0 && e.RowIndex >= 0)
{
e.Paint(e.ClipBounds, DataGridViewPaintParts.All);

Rectangle indexRect = e.CellBounds;
indexRect.Inflate(-2, -2);
TextRenderer.DrawText(e.Graphics,
(e.RowIndex + 1).ToString(),
e.CellStyle.Font,
indexRect,
e.CellStyle.ForeColor,
TextFormatFlags.Right | TextFormatFlags.VerticalCenter);
e.Handled = true;
}
}
RowPostPaintイベントを活用する方法
VB.NET
Private Sub dgv1_RowPostPaint(ByVal sender As Object, _
ByVal e As DataGridViewRowPostPaintEventArgs) _
Handles dgv1.RowPostPaint
Dim dgv As DataGridView = CType(sender, DataGridView)
If dgv.RowHeadersVisible Then
Dim rect As New Rectangle(e.RowBounds.Left, e.RowBounds.Top, _
dgv.RowHeadersWidth, e.RowBounds.Height)
rect.Inflate(-2, -2)
TextRenderer.DrawText(e.Graphics, _
(e.RowIndex + 1).ToString(), _
e.InheritedRowStyle.Font, _
rect, _
e.InheritedRowStyle.ForeColor, _
TextFormatFlags.Right Or TextFormatFlags.VerticalCenter)
End If
End Sub
C#
private void dgv1_RowPostPaint(object sender,
DataGridViewRowPostPaintEventArgs e)
{
DataGridView dgv = (DataGridView)sender;
if (dgv.RowHeadersVisible)
{
Rectangle rect = new Rectangle(
e.RowBounds.Left, e.RowBounds.Top,
dgv.RowHeadersWidth, e.RowBounds.Height);
rect.Inflate(-2, -2);
TextRenderer.DrawText(e.Graphics,
(e.RowIndex + 1).ToString(),
e.InheritedRowStyle.Font,
rect,
e.InheritedRowStyle.ForeColor,
TextFormatFlags.Right | TextFormatFlags.VerticalCenter);
}
}

■■■