C# DataGridView控件设置序号或显示行号

步骤一:

确认DataGridView控件的RowHeadersVisible属性为true;(设置第一列/列头不隐藏)

步骤二:

编写RowPostPaint事件方法

private void dgv_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            Rectangle rectangle = new Rectangle(e.RowBounds.Location.X,
                e.RowBounds.Location.Y,
                dgv_data.RowHeadersWidth - 4,
                e.RowBounds.Height);
            TextRenderer.DrawText(e.Graphics, (e.RowIndex + 1).ToString(),
                dgv_data.RowHeadersDefaultCellStyle.Font,
                rectangle,
                dgv_data.RowHeadersDefaultCellStyle.ForeColor,
                TextFormatFlags.VerticalCenter | TextFormatFlags.Right);
        }

附:

 Rectangle(int x, int y, int width, int height);该方法是用指定的位置和大小初始化 System.Drawing.Rectangle 类的新实例。

参数说明:    x:   矩形左上角的 x 坐标。  y:  矩形左上角的 y 坐标。 width:  矩形的宽度。 height:  矩形的高度。

TextRenderer.DrawText(IDeviceContext dc, string text, Font font, Rectangle bounds, Color foreColor, TextFormatFlags flags);该方法用于绘制指定的文本,使用指定的设备上下文、 字体、 颜色和格式设置的说明指定的边界内。

参数说明: dc: 在其中绘制文本的设备上下文。  text: 要绘制的文本。 font: System.Drawing.Font 将应用于所绘制文本。        bounds:  System.Drawing.Rectangle 表示文本的边界。  foreColor: System.Drawing.Color 将应用于所绘制文本。 flags: System.Windows.Forms.TextFormatFlags 值的按位组合。

步骤三:

在Designer文件中为DataGridView控件绑定RowPostPaint事件

 this.dgv_data.RowPostPaint += new System.Windows.Forms.DataGridViewRowPostPaintEventHandler(this.dgv_RowPostPaint); 

   效果图:

        

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

tiegenZ

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值