显示DataGrid序号的一个适用的方法
2024-07-21 02:20:09
供稿:网友
 
我在网上查了好几个例子,如果数据量小的话没有问题,一旦数据量大,显示特别慢,还有个缺点就是拖动行高时行号不随行高的变化而变动,出现是几个序号在一个单元格中显示。我自己对他们的算法进行总结,写出一个效果比较不错的带序号的datagrid。原理:只显示表格中显示行的序号,并且拖动行,行号一起移动。
override protected void onpaint(painteventargs e)
{
base.onpaint(e);
 try
 {
 if(this.datasource!=null)
 { 
 int ydelta; 
 system.drawing .rectangle cell=this.getcellbounds(0,0);
 int y=cell.top +2;
 e.graphics.drawstring("编号", this.font, new solidbrush(color.black), 8, y-18); //
 if(this.visiblerowcount >0)//只在有记录集时在表格中显示序号
 { 
 currencymanager cm;
 cm = (currencymanager) this.bindingcontext[this.datasource, this.datamember]; 
 if(cm.count >0)
 { 
 int nrow=-1;
 y=41; //为第一行默认高度
 while(nrow<0)
 {
nrow=this.hittest (8,y).row ;
 y++;
 }
 int ncount=0;
 while(y<this.height && ncount<this.visiblerowcount )
 {
 string text = string.format("{0}", nrow+ncount+1); 
 e.graphics.drawstring(text, this.font, new solidbrush(color.black), 10, y); 
 ydelta = this.getcellbounds( nrow+ncount,0).height + 1;//****表示一行高度的参数
 y += ydelta; 
//如果下面有子行显示序号的区分显示 
 if(this.isexpanded (nrow+ncount)&& nrow+ncount+1<cm.count ) {
 y+=this.getcellbounds (nrow+ncount+1,0).height +3;
 }
 ncount++; 
 }
}
 }
 }
 }
 catch
 {}
}
重载了datagrid中的paint,这样用起来会特别方便,区区雕虫小技,希望和大家共同分享。