合计时效果如下:
平均值时的效果:
文字显示时的效果:
因为一些原因源代码不能完全公布,所以这里只谈下实现思路:因为datagridview控件本身没有自动合计的功能,而在每次绑定时向网格底部插入一空行实现合计的办法既不方便又不灵活,而且不能达到时刻可以看到合计的效果,必须每次都手动拖动滚动条到底端来看,所以这种实现办法不够理想.就想了以下一种方法来实现.用一个PANEL和一个DAGRIDVIEW组成一个复合控件,在DATAGRIDVIEW的PAINT方法中,来手工绘制合计.绘制的时候有2个难点,一是合计的数字,一是分隔线.数字采用DATATABLE.COMPUTE()方法来得到,至于显示的位置就和绘制线条的位置归属于一个问题了.需要得到可见的第一列的HIDDEN的宽,然后从此列开始,累计每列的宽度和(第一可见列要用COLUMNWIDTH - HIDDEN),这样我们就可以比较方便的得到分隔线的位置与数字的位置了.因为时间问题,先谈到这里,如有需要进一步讨论,可以留言给我.
部分源代码:
private DataTable SourceDataTable; // GRID数据源 private bool _IsShowFooter = true ; // GRID是否显示脚注 private Color _GridFooterBackColor = SystemColors.Info; // GRIDFOOTER背景色 private String _GridFooterHeader = " SUM " ; private TotalType _GridFooterTotalType; private string _CustomerString; private bool _IsShowSumHeader = true ; // 是否显示合计标题 public enum TotalType ... { SUM = 0,//求和 AVG = 1,//均值 CUSTOMER//自定义字符串 } public JCSGridControl() ... { InitializeComponent(); this.Grid.ScrollBars = ScrollBars.Both; this.GridFooter.BackColor = this.Grid.BackgroundColor; if (this._IsShowFooter) ...{ GridFooter.Visible = true; //this.Grid.Gridvscroollbar.BringToFront(); this.GridFooter.Paint += new PaintEventHandler(GridFooter_Paint); } else ...{ GridFooter.Visible = false; this.Grid.ScrollBars = ScrollBars.Vertical; } this.Grid.Paint += new PaintEventHandler(Grid_Paint); this.Grid.RowPostPaint += new DataGridViewRowPostPaintEventHandler(Grid_RowPostPaint); } void Grid_Paint( object sender, PaintEventArgs e) ... { if (!this.DesignMode) DrawSumColumnLine(); } // 绘制行号 private void Grid_RowPostPaint( object sender, DataGridViewRowPostPaintEventArgs e) ... { if (!this.Grid.RowHeadersVisible) return; if (this.Grid.RowHeadersWidth < 40) return; //定义一个矩形 Rectangle rectangle = new Rectangle(e.RowBounds.Location.X, e.RowBounds.Location.Y, Grid.RowHeadersWidth - 1, e.RowBounds.Height); TextRenderer.DrawText(e.Graphics, (e.RowIndex + 1).ToString(), Grid.RowHeadersDefaultCellStyle.Font, rectangle, Grid.RowHeadersDefaultCellStyle.ForeColor, TextFormatFlags.VerticalCenter | TextFormatFlags.Right); }