开源DataGridView扩展(4) 自定义带序号的行首

      其实,在很多时候我们对Excel的使用习惯会影响着我们的一些用户体验。那今天要介绍的就是像Excel那样表格行头会有序号,如下:

r0

一、实现原理及步骤

       其实很简单,要首先去了解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();
        }
可以了,这样就实现了我们需要的简单的效果了,不过这只是简单的实现,以后要增加图例或者其他要求的话,直接在扩展里面绘制就行了。

二、需要注意的地方

       我们先来看两种效果:

r1

r2

        从两幅图看来,主要的区别在于在索引文字的显示位置和对齐方式。图一时使用graphics.DrawString的,后者是使用TextRenderer来做的,两种效果有明显的不同,这就是本次例子要注意的地方;TextRenderer绘制出来的文字通常情况下是按照中间位置并且不会影响到区域的本来的背景等,所以建议在更多的情况下用TextRenderer来绘制文本。

三、演示程序及源码

演示程序:04[20120505]DataGridViewRowHeaderCellEx@DataGridViewEx.rar

开源项目:http://sourceforge.net/p/datagridviewex/code-0/3/tree/trunk/DataGridViewEx/

 

转载于:https://www.cnblogs.com/gxjiang/archive/2012/05/05/2485381.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值