其实,在很多时候我们对Excel的使用习惯会影响着我们的一些用户体验。那今天要介绍的就是像Excel那样表格行头会有序号,如下:
一、实现原理及步骤
其实很简单,要首先去了解DataGridView中表格的构造;通过前面我们的摸索,我们知道在Column中有HeaderCell,那么反过来,行首,是不是应该也有行表头单元格HeaderCell呢?
从调研中,我发现在DataGridView中有RowTemplate一个属性,找到这个属性我就立马见到了曙光;再进一步尝试之后发现了RowTemplate中有HeaderCell属性,这就是我要寻找的行表头的单元格样式,那么原理就是将这个行表头单元格重写。
public class DataGridViewRowHeaderCellEx:DataGridViewRowHeaderCell { protected override void Paint( System.Drawing.Graphics graphics, System.Drawing.Rectangle clipBounds, System.Drawing.Rectangle cellBounds, int rowIndex, DataGridViewElementStates cellState, object value, object formattedValue, string errorText, DataGridViewCellStyle cellStyle, DataGridViewAdvancedBorderStyle advancedBorderStyle, DataGridViewPaintParts paintParts) { base.Paint(graphics, clipBounds, cellBounds, rowIndex, cellState, value, formattedValue, errorText,cellStyle, advancedBorderStyle, paintParts); //graphics.DrawString(rowIndex.ToString(), this.DataGridView.Font, new SolidBrush(Color.Blue),cellBounds); TextRenderer.DrawText(graphics, (rowIndex+1).ToString(), DataGridView.Font, cellBounds, Color.Black); } }
从上面的代码来看,真的很简单的实现了RowHeaderCell的重写了,然后在注册:public DataGridViewEx() : base() { this.SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.UserPaint | ControlStyles.OptimizedDoubleBuffer | ControlStyles.ResizeRedraw, true); this.CellFormatterRegister = new DataGridCellFormatter(); this.RowTemplate.HeaderCell = new DataGridViewRowHeaderCellEx(); }可以了,这样就实现了我们需要的简单的效果了,不过这只是简单的实现,以后要增加图例或者其他要求的话,直接在扩展里面绘制就行了。
二、需要注意的地方
我们先来看两种效果:
从两幅图看来,主要的区别在于在索引文字的显示位置和对齐方式。图一时使用graphics.DrawString的,后者是使用TextRenderer来做的,两种效果有明显的不同,这就是本次例子要注意的地方;TextRenderer绘制出来的文字通常情况下是按照中间位置并且不会影响到区域的本来的背景等,所以建议在更多的情况下用TextRenderer来绘制文本。
三、演示程序及源码
演示程序:04[20120505]DataGridViewRowHeaderCellEx@DataGridViewEx.rar
开源项目:http://sourceforge.net/p/datagridviewex/code-0/3/tree/trunk/DataGridViewEx/