近日在网上搜到一些如何在WinForm的DataGrid上显示行号的资料,因此自己也写了一段代码,因为是在前人实践的基础上做了些修改,所以不敢独享。如下:
/// <summary>
/// 可以显示行号的DataGrid
/// </summary>
public class HDataGrid : System.Windows.Forms.DataGrid
{
public HDataGrid():base()
{}
private bool _DisplayRowNumber = false;
/// <summary>
/// 控制是否显示行号
/// </summary>
[Browsable(true),DefaultValue(false),Description("是否显示行号")]
public bool DisplayRowNumber
{
get { return _DisplayRowNumber; }
set {
_DisplayRowNumber = value;
this.Invalidate();
}
}
/// <summary>
/// 重载OnPaint方法显示行号
/// </summary>
/// <param name="e"></param>
protected override void OnPaint(System.Windows.Forms.PaintEventArgs e)
{
base.OnPaint (e);
//显示行号
if (DisplayRowNumber && this.RowHeadersVisible && this.VisibleColumnCount > 0)
{
if (this.DataSource == null) return;
int iRowNumStart = this.VertScrollBar.Value;
int yPos = 0;
int iRowNumEnd = iRowNumStart + this.VisibleRowCount;
while(iRowNumStart < iRowNumEnd)
{
yPos = this.GetCellBounds(iRowNumStart++,0).Y + 2;
string strRowNum = string.Format(" {0}",iRowNumStart);
e.Graphics.DrawString(strRowNum,this.Font ,new System.Drawing.SolidBrush(System.Drawing.Color.Black), 6, yPos);
}
}
}
}
/// 可以显示行号的DataGrid
/// </summary>
public class HDataGrid : System.Windows.Forms.DataGrid
{
public HDataGrid():base()
{}
private bool _DisplayRowNumber = false;
/// <summary>
/// 控制是否显示行号
/// </summary>
[Browsable(true),DefaultValue(false),Description("是否显示行号")]
public bool DisplayRowNumber
{
get { return _DisplayRowNumber; }
set {
_DisplayRowNumber = value;
this.Invalidate();
}
}
/// <summary>
/// 重载OnPaint方法显示行号
/// </summary>
/// <param name="e"></param>
protected override void OnPaint(System.Windows.Forms.PaintEventArgs e)
{
base.OnPaint (e);
//显示行号
if (DisplayRowNumber && this.RowHeadersVisible && this.VisibleColumnCount > 0)
{
if (this.DataSource == null) return;
int iRowNumStart = this.VertScrollBar.Value;
int yPos = 0;
int iRowNumEnd = iRowNumStart + this.VisibleRowCount;
while(iRowNumStart < iRowNumEnd)
{
yPos = this.GetCellBounds(iRowNumStart++,0).Y + 2;
string strRowNum = string.Format(" {0}",iRowNumStart);
e.Graphics.DrawString(strRowNum,this.Font ,new System.Drawing.SolidBrush(System.Drawing.Color.Black), 6, yPos);
}
}
}
}