如何为datagridview加上序号

如何为datagridview加上序号,第1张

你可以重写DataGridView的OnRowPostPaint方法或者直接在DataGridView的RowPostPaint事件里写,如下(重写DataGridView的OnRowPostPaint方法)

using System

using System.Text

using System.Windows.Forms

using System.Drawing

namespace Test

{

class DataGridViewEx : DataGridView

{

SolidBrush solidBrush

public DataGridViewEx()

{

solidBrush = new SolidBrush(this.RowHeadersDefaultCellStyle.ForeColor)

}

protected override void OnRowPostPaint(DataGridViewRowPostPaintEventArgs e)

{

e.Graphics.DrawString((e.RowIndex + 1).ToString(), e.InheritedRowStyle.Font, solidBrush, e.RowBounds.Location.X + 15, e.RowBounds.Location.Y + 5)

base.OnRowPostPaint(e)

}

}

}

最简单的方法是在Datagridview的事件RowPostPaint事件下面添加如下代码即可

private void dataGridView1_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)

{

SolidBrush b = new SolidBrush(this.dataGridView1.RowHeadersDefaultCellStyle.ForeColor)

e.Graphics.DrawString((e.RowIndex + 1).ToString(System.Globalization.CultureInfo.CurrentUICulture), this.dataGridView1.DefaultCellStyle.Font, b, e.RowBounds.Location.X + 20, e.RowBounds.Location.Y + 4)

}

代码写在 DataGridView的RowPostPaint事件中

//DataGridView控件添加序号:事件RowPostPaint

private void dataGridView1_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)

{

DataGridView temp = (DataGridView)sender

using (SolidBrush b = new SolidBrush(temp.RowHeadersDefaultCellStyle.ForeColor))

{

e.Graphics.DrawString(Convert.ToString(e.RowIndex + 1, System.Globalization.CultureInfo.CurrentUICulture), e.InheritedRowStyle.Font, b, e.RowBounds.Location.X + 15, e.RowBounds.Location.Y + 5)

}

}

// DataGridView序号列的标题显示:序号 Paint 事件

private void dataGridView1_Paint(object sender, PaintEventArgs e)

{

DataGridView temp = (DataGridView)sender

using (SolidBrush b = new SolidBrush(temp.RowHeadersDefaultCellStyle.ForeColor))

{

e.Graphics.DrawString("序号", temp.Font, b, 8, 5)

}

}

在datagridview上显示行号

1,先在加入如下代码

private void dataGridView1_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)

{

Rectangle rectangle = new Rectangle(e.RowBounds.Location.X,

e.RowBounds.Location.Y,

dataGridView1.RowHeadersWidth - 4,

e.RowBounds.Height)

TextRenderer.DrawText(e.Graphics, (e.RowIndex + 1).ToString(),

dataGridView1.RowHeadersDefaultCellStyle.Font,

rectangle,

dataGridView1.RowHeadersDefaultCellStyle.ForeColor,

TextFormatFlags.VerticalCenter | TextFormatFlags.Right)

}

2,然后再在From1.Designer.cs文件中加入如下代码,就行了。

this.dataGridView1.RowPostPaint += new System.Windows.Forms.DataGridViewRowPostPaintEventHandler(this.dataGridView1_RowPostPaint)


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/bake/11746770.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-18
下一篇 2023-05-18

发表评论

登录后才能评论

评论列表(0条)

保存