同样是重载OnPaint 方法,但是方法应该是比较巧妙的!而且不用担心标题是不是有显示,也不用去计算坐标,很方便的说!
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
if(this.DataSource!=null)
{
if( this.VisibleRowCount == 0 )return;
Rectangle currRct;
int iRowCount = this.VisibleRowCount; //这边有个错误 VisibleRowCount 仅限于可见的行
string sText = "";
int nowY = 0;
for( int i = 0 ; i < iRowCount ; i++ )
{
currRct = (Rectangle)this.GetCellBounds( i, 0 );
nowY = currRct.Y + 2;
sText = string.Format( " {0}", i+1 );
e.Graphics.DrawString( sText, this.Font, new SolidBrush(Color.Black), 10, nowY );
}
}
}
===================================================================
上文发生错误的地方在于this.VisibleRowCount ,由VisibleRowCount 仅取到可见的行数,所以当行数超过了可视范围时,其余的行号就没有画出来了,那这个取行数的方法现在已做更正,哪位朋友如果说有更好的方法可以一起讨论.
更正后的实现方法如下:
===================================================================
using System;
using System.Data;
using System.Drawing;
using System.Windows.Forms;
namespace MyControls
{
public class MyDataGrid : DataGrid
{
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
DrawRowNumber( e );
}
private void DrawRowNumber( PaintEventArgs e )
{
if( this.DataSource!=null && this.VisibleRowCount != 0 )
{
Rectangle currRct;
int iRowCount = 0;
switch( this.DataSource.GetType().ToString() )
{
case "System.Data.DataSet": //绑定对象为DataSet
iRowCount = ((DataSet)this.DataSource).Tables[this.DataMember].Rows.Count;
break;
case "System.Data.DataTable": //绑定对象为DataTable
iRowCount = ((DataTable)this.DataSource).Rows.Count;
break;
case "System.Data.DataView": //绑定对象为DataView
iRowCount = ((DataView)this.DataSource).Count;
break;
default: //其他的对象
return;
}
for( int i = 0 ; i < iRowCount ; i++ )
{
currRct = (Rectangle)this.GetCellBounds( i, 0 );
e.Graphics.DrawString( string.Format( " {0}", i+1 ) , this.Font, new SolidBrush(Color.Black), 10, currRct.Y + 2 );
}
}
}
}