如何为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)

}

System.Data.DataTable table = new DataTable()

System.Data.DataColumn column = new DataColumn()

column.ColumnName = "序号"

column.AutoIncrement = true

column.AutoIncrementSeed = 1

column.AutoIncrementStep = 1

table.Columns.Add(column)

table.Merge(ds.Tables[0])

datagridview1.DataSource = table

datagridview1.Columns["序号"].DisplayIndex = 0//调整列顺序

复制过来的,希望对你有帮助,c# 支持 隐式的转换,你也可以用Convert 来转换类型

你也可以使用:

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)

{if (e.Row.RowIndex >= 0)

{

e.Row.Cells[0].Text = Convert.ToString(e.Row.DataItemIndex + 1)

}

}


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

原文地址:https://54852.com/bake/11408557.html

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

发表评论

登录后才能评论

评论列表(0条)

    保存