有很多种方法。
1、可以在DataGridView控件中的RowStateChanged事件改变行标题单元格的值(Row.HeaderCell.Value)
/// <summary>
/// 行状态更改时发生
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void dataGridView1_RowStateChanged(object sender, DataGridViewRowStateChangedEventArgs e)
{
//e.Row.HeaderCell.Value = string.Format("{0}", e.Row.Index + 1);
e.Row.HeaderCell.Value = (e.Row.Index + ).ToString();//添加行号
}
2、可以在DataGridView控件中的RowPostPaint事件例进行设置,TextRenderer类的DrawText()方法使用指定的设备上下文、字体、颜色和格式说明在指定界限中绘制指定文本。
/// <summary>
/// 所有单元格绘制后,执行 行绘制时发生
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void dataGridView1_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
{
//
System.Drawing.Rectangle rectangle = new Rectangle(e.RowBounds.Location.X, e.RowBounds.Y, this.dataGridView1.RowHeadersWidth - , this.dataGridView1.ColumnHeadersHeight);
TextRenderer.DrawText(e.Graphics, (e.RowIndex + ).ToString(), this.dataGridView1.RowHeadersDefaultCellStyle.Font, rectangle, this.dataGridView1.RowHeadersDefaultCellStyle.ForeColor, TextFormatFlags.VerticalCenter | TextFormatFlags.Right);//”TextFormatFlags.VerticalCenter | TextFormatFlags.Right“中“|”有增加的作用,此处添加了两种文本字符格式样式
}
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 != )
{
gv.IndicatorWidth = width;
}
else
{
gv.IndicatorWidth = ;
}
//}
//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 > -)
{
e.Info.DisplayText = (e.RowHandle + ).ToString();
}
}