有很多种方法。
1、可以在DataGridView控件中的RowStateChanged事件改变行标题单元格的值(Row.HeaderCell.Value)
1 /// <summary> 2 /// 行状态更改时发生 3 /// </summary> 4 /// <param name="sender"></param> 5 /// <param name="e"></param> 6 private void dataGridView1_RowStateChanged(object sender, DataGridViewRowStateChangedEventArgs e) 7 {
8 //e.Row.HeaderCell.Value = string.Format("{0}", e.Row.Index + 1); 9 e.Row.HeaderCell.Value = (e.Row.Index + 1).ToString();//添加行号 10 }
2、可以在DataGridView控件中的RowPostPaint事件例进行设置,TextRenderer类的DrawText()方法使用指定的设备上下文、字体、颜色和格式说明在指定界限中绘制指定文本。
1 /// <summary> 2 /// 所有单元格绘制后,执行 行绘制时发生 3 /// </summary> 4 /// <param name="sender"></param> 5 /// <param name="e"></param> 6 private void dataGridView1_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e) 7 { 8 // 9 System.Drawing.Rectangle rectangle = new Rectangle(e.RowBounds.Location.X, e.RowBounds.Y, this.dataGridView1.RowHeadersWidth - 4, this.dataGridView1.ColumnHeadersHeight); 10 TextRenderer.DrawText(e.Graphics, (e.RowIndex + 1).ToString(), this.dataGridView1.RowHeadersDefaultCellStyle.Font, rectangle, this.dataGridView1.RowHeadersDefaultCellStyle.ForeColor, TextFormatFlags.VerticalCenter | TextFormatFlags.Right);//”TextFormatFlags.VerticalCenter | TextFormatFlags.Right“中“|”有增加的作用,此处添加了两种文本字符格式样式 11 }
dev 的DevExpress.XtraGrid.Views.Grid.GridView控件添加行号:
/// <summary> /// GridView 显示行号 设置行号列的宽度 /// </summary> /// <param name="gv">GridView 控件名称</param> /// <param name="width">行号列的宽度 如果为null或为0 默认为30</param> public void DrawRowIndicator(DevExpress.XtraGrid.Views.Grid.GridView gv, int width) { gv.CustomDrawRowIndicator += new DevExpress.XtraGrid.Views.Grid.RowIndicatorCustomDrawEventHandler(gv_CustomDrawRowIndicator); //if (width != null) //{ if (width != 0) { gv.IndicatorWidth = width; } else { gv.IndicatorWidth = 30; } //} //else //{ // gv.IndicatorWidth = 30; //} } /// <summary> /// 行号设置 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void gv_CustomDrawRowIndicator(object sender, DevExpress.XtraGrid.Views.Grid.RowIndicatorCustomDrawEventArgs e) { if (e.Info.IsRowIndicator && e.RowHandle > -1) { e.Info.DisplayText = (e.RowHandle + 1).ToString(); } }