为DataGridView增加行号

本文介绍如何为DataGridView控件手动添加行号,通过处理RowPostPaint事件实现不同位数行号的绘制,确保行号随行选中状态变化而变化。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

     DataGridView本身没有行号,所以要想得到行号,需要对第一列进行重绘。我们可以在rowspostpaint事件中增加处理代码。

    ''' <summary>

    ''' 给GridView添加行号

    ''' </summary>

    ''' <param name="sender"></param>

    ''' <param name="e"></param>

    ''' <remarks></remarks>

    Private Sub DataGridView1_RowPostPaint(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewRowPostPaintEventArgs) Handles gridOrder.RowPostPaint

        GridNO.NO(DataGridView1, e)

    End Sub

Public Class GridNO

    Public Shared Sub NO(ByVal dv As DataGridView, ByVal e As System.Windows.Forms.DataGridViewRowPostPaintEventArgs)

        '在列前面加上行号

        '在DataGridView的RowPostPaint事件中这样调用:GridNo.NO(datagridview1,e)

 

        Dim Color As Color = dv.RowHeadersDefaultCellStyle.ForeColor

        If dv.Rows(e.RowIndex).Selected Then

            Color = dv.RowHeadersDefaultCellStyle.SelectionForeColor

        Else

            Color = dv.RowHeadersDefaultCellStyle.ForeColor

        End If

 

        Dim b As SolidBrush = New SolidBrush(Color)

        If e.RowIndex < 9 Then

            e.Graphics.DrawString((e.RowIndex + 1).ToString(), e.InheritedRowStyle.Font, b, e.RowBounds.Location.X + 22, e.RowBounds.Location.Y + 6)

        ElseIf e.RowIndex < 99 Then

            e.Graphics.DrawString((e.RowIndex + 1).ToString(), e.InheritedRowStyle.Font, b, e.RowBounds.Location.X + 19, e.RowBounds.Location.Y + 6)

        ElseIf e.RowIndex < 999 Then

            e.Graphics.DrawString((e.RowIndex + 1).ToString(), e.InheritedRowStyle.Font, b, e.RowBounds.Location.X + 16, e.RowBounds.Location.Y + 6)

        ElseIf e.RowIndex < 9999 Then

            e.Graphics.DrawString((e.RowIndex + 1).ToString(), e.InheritedRowStyle.Font, b, e.RowBounds.Location.X + 13, e.RowBounds.Location.Y + 6)

        Else

            e.Graphics.DrawString((e.RowIndex + 1).ToString(), e.InheritedRowStyle.Font, b, e.RowBounds.Location.X + 10, e.RowBounds.Location.Y + 6)

        End If

        b.Dispose()

    End Sub

End Class

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值