扩展 DataGridView 的功能(一)

扩展的功能:

1.显示行号
2.加入可以输入文字的 DataGridViewComboBoxCell
2.可分组折叠
3.合并单元格
4.Undo/Redo的支持
5.其他。。。。。
定义类

    /// <summary>
    /// 扩展的 DataGridView
    /// </summary>

    public class DataGridViewEx : DataGridView

    {

    }

先来一个最简单的:显示行号
这 里我们用到了一个事件 RowPostPaint, 查看MSDN后可知该事件是在“绘制 DataGridViewRow后发生”
DataGridView 在绘制 DataGridViewRow 时没有处理行号, 那就由 DataGridViewEx 来处理吧
知道了原理,添加行号就很简单了, DrawString 就OK。
给出主要的代码实现 :

        void DataGridViewEx_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)

        {

            if (showRowHeaderNumbers)

            {

                string title = (e.RowIndex + 1).ToString();

                Brush bru = Brushes.Black;

                e.Graphics.DrawString(title, DefaultCellStyle.Font,

                    bru, e.RowBounds.Location.X + RowHeadersWidth / 2 - 4, e.RowBounds.Location.Y + 4);

            }

        }

完成后的效果: