【C#】datagridview里加一列序号

本文介绍了如何使用C#语言处理数据源,并通过代码实现自动生成行号的功能。首先,演示了如何创建一个新的数据表,并将原始数据源合并到新表中。接着,详细解释了在DataGridView控件中自动生成行号的方法,包括使用RowPostPaint事件和CellPainting事件来实现这一目标。
方法一:处理数据源,假设原来绑定的数据源为DataTable dt
C# code
?
1
2
3
4
5
6
7
8
9
DataTable ndt =  new  DataTable();
DataColumn dc =  new  DataColumn();
dc.ColumnName =  "序号" ;
dc.AutoIncrement =  true ;
dc.AutoIncrementSeed = 1;
dc.AutoIncrementStep = 1;
ndt.Columns.Add(dc);
ndt.Merge(dt);
dataGridView1.DataSource = ndt;


方法二:
C# code
?
1
2
3
4
5
6
7
8
9
10
11
12
private  void  dataGridView1_RowPostPaint( object  sender, DataGridViewRowPostPaintEventArgs e)
{
     using  (SolidBrush b =  new  SolidBrush(dataGridView1.RowHeadersDefaultCellStyle.ForeColor))
     {
         string  linenum = e.RowIndex.ToString();
         int  linen = 0;
         linen = Convert.ToInt32(linenum) + 1;
         string  line = linen.ToString();
         e.Graphics.DrawString(line, e.InheritedRowStyle.Font, b, e.RowBounds.Location.X + 20, e.RowBounds.Location.Y + 5);
         SolidBrush B =  new  SolidBrush(Color.Red);
     }
}


方法三:
C# code
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
private  void  dataGridView1_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 ;
    
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值