DataGridView 的合计行源码,需要的来Copy吧!

曾经几时,我一直因为一个合计行抓狂。日常表格显示中,合计行可以说是不可缺少的,但好像没有听说过有现成的可用。甚至有些是要收费的。就如我去年年初说过的那样,几行代码而也,值不值钱的,看有没有用了。今天就把我自己写的一个合计行源码放出来。

我使用的是用一个DataGridView 来处理合计,但这个DataGridView保持只有一行,而且和绑定的DataGridView数据相关。简单点,就是你绑定后,只需要对存放数据的DataGridView进行处理就好了。当然,由于长期自己开发,很多地方写的不是很严谨,需要的根据需要自己改吧。

不过这里要说明一下,其中的Cls_DataGridView 其实就是一个DataGridView,只是我自己重写后加了些功能,等有空另外再粘出来了,也是很有用的。

用法,设置my_fatherCDGV为存放数据的 DataGridView,设置my_SumColumns 为需要进行合计的列(如1,2,4),当然这些列一定要是数字,不然会报错。最后不要忘了在窗口启动时调用一下my_Show,否则合计行不起作用。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.Windows.Forms;

namespace WaterClassLibrary.HaveRun
{
    /// <summary>
    /// 合计行
    /// </summary>
    public class cls_DataGridViewTotalFoot : Cls_DataGridView
    {

        [Category("自定义属性"), Browsable(true), Description("附属的Cls_DataGridView")]
        public Cls_DataGridView my_fatherCDGV
        {
            get;
            set;
        }

        [Category("自定义属性"), Browsable(true), Description("要计算合计的列,用,分隔;0无效")]
        public string my_SumColumns { get; set; }

        /// <summary>
        /// 标记是否执行列宽设置
        /// </summary>
        public bool bol_SetColumnsWidth = true;

        /// <summary>
        /// 设置合计行可用
        /// </summary>
        public void my_Show()
        {
            //调整控件            
            my_fatherCDGV.ColumnWidthChanged += new DataGridViewColumnEventHandler(fatherCDGV_ColumnWidthChanged);
            my_fatherCDGV.RowsAdded += new DataGridViewRowsAddedEventHandler(fatherCDGV_RowsAdded);
            my_fatherCDGV.CellValueChanged += new DataGridViewCellEventHandler(my_fatherCDGV_CellValueChanged);
            my_fatherCDGV.RowsRemoved += new DataGridViewRowsRemovedEventHandler(fatherCDGV_RowsRemoved);
            my_fatherCDGV.RowHeadersWidthChanged += new EventHandler(fatherCDGV_RowHeadersWidthChanged);
            my_fatherCDGV.SelectionChanged += new EventHandler(my_fatherCDGV_SelectionChanged);
            my_fatherCDGV.DataSourceChanged += My_fatherCDGV_DataSourceChanged;
            my_fatherCDGV.CellEndEdit += My_fatherCDGV_CellEndEdit;            
            my_fatherCDGV.ScrollBars = ScrollBars.Vertical;            
            this.ScrollBars = ScrollBars.Horizontal;
            this.AllowUserToAddRows = false;
            this.AllowUserToResizeColumns = false;
            this.ReadOnly = true;
            this.RowHeadersVisible = my_fatherCDGV.RowHeadersVisible;
            this.AllowUserToResizeColumns = false;
            this.ColumnHeadersVisible = false;
            my_fatherCDGV.ColumnAdded += new DataGridViewColumnEventHandler(my_fatherCDGV_ColumnAdded);
            my_fatherCDGV.ColumnRemoved += new DataGridViewColumnEventHandler(my_fatherCDGV_ColumnRemoved);
            this.RowHeadersWidthChanged += new EventHandler(cls_DataGridViewTotalFoot_RowHeadersWidthChanged);
            my_fatherCDGV.Resize += new EventHandler(my_fatherCDGV_Resize);
            my_fatherCDGV.Scroll += new ScrollEventHandler(my_fatherCDGV_Scroll);
            my_fatherCDGV.Paint += new PaintEventHandler(my_fatherCDGV_Paint);
            my_fatherCDGV.DefaultCellStyleChanged += My_fatherCDGV_DefaultCellStyleChanged;
            this.DataError += new System.Windows.Forms.DataGridViewDataErrorEventHandler(this.Cls_DataGridViewTotalFoot_DataError);
            this.SelectionChanged += new System.EventHandler(this.cls_DataGridViewTotalFoot_SelectionChanged);
            if (my_fatherCDGV.Columns.Count > 0)
            {
                NewColumns();
                ComputeSum();
            }
            this.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells;
            for (int i = 0; i < my_fatherCDGV.ColumnCount; i++)
            {
                this.Columns[i].DefaultCellStyle = my_fatherCDGV.Columns[i].DefaultCellStyle;
            }

        }       

        private void My_fatherCDGV_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            ComputeSum();
        }

        private void My_fatherCDGV_DataSourceChanged(object sender, EventArgs e)
        {
            ComputeSum(); 
        }

        private void My_fatherCDGV_DefaultCellStyleChanged(object sender, EventArgs e)
        {
            for(int i = 0; i < my_fatherCDGV.ColumnCount; i++)
            {
                this.Columns[i].DefaultCellStyle = my_fatherCDGV.Columns[i].DefaultCellStyle;
            }
        }

        void my_fatherCDGV_Paint(object sender, PaintEventArgs e)
        {
            RefrashMe();
        }
        void my_fatherCDGV_Scroll(object o,ScrollEventArgs e)
        {
            if (e.ScrollOrientation == ScrollOrientation.HorizontalScroll)
            {
                this.HorizontalScrollingOffset = e.NewValue;
            }
        }

        void my_fatherCDGV_SelectionChanged(object sender, EventArgs e)
        {
            this.SelectionChanged -= new System.EventHandler(this.cls_DataGridViewTotalFoot_SelectionChanged);
            if (my_fatherCDGV.CurrentCell == null) { return; }
            this.ClearSelection();
            if (this.Rows.Count > 0)
            {
                this.Rows[0].Cells[my_fatherCDGV.CurrentCell.ColumnIndex].Selected = true;
            }
            this.SelectionChanged += new System.EventHandler(this.cls_DataGridViewTotalFoot_SelectionChanged);

        }
        
        void my_fatherCDGV_Resize(object sender, EventArgs e)
        {
            RefrashMe();
        }       
        void my_fatherCDGV_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
           ComputeSum();
        }

        void cls_DataGridViewTotalFoot_RowHeadersWidthChanged(object sender, EventArgs e)
        {
            this.RowHeadersWidth = my_fatherCDGV.RowHeadersWidth;
        }

        void my_fatherCDGV_ColumnRemoved(object sender, DataGridViewColumnEventArgs e)
        {
            NewColumns();
        }

        void my_fatherCDGV_ColumnAdded(object sender, DataGridViewColumnEventArgs e)
        {
            NewColumns();
        }

        void fatherCDGV_RowHeadersWidthChanged(object sender, EventArgs e)
        {            
            SetColumnsSize();            
        }

        protected override void OnScroll(ScrollEventArgs e)
        {//处理滚动条
            base.OnScroll(e);
            if (e.ScrollOrientation == ScrollOrientation.HorizontalScroll)
            {
                my_fatherCDGV.HorizontalScrollingOffset = e.NewValue;
            }
        }

        //protected override void OnLayout(LayoutEventArgs e)
        //{
        //    base.OnLayout(e);
        //    RefrashMe();
        //}
        
        void fatherCDGV_RowsRemoved(object sender, DataGridViewRowsRemovedEventArgs e)
        {
            //SetColumnsSize();
            ComputeSum();
        }

        void fatherCDGV_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
        {
            //            SetColumns();           
            ComputeSum();
        }
        
        

        /// <summary>
        /// 计算合计数
        /// </summary>
        private void ComputeSum()
        {
            if (my_fatherCDGV.Columns != null && my_SumColumns != null && my_fatherCDGV.Columns.Count >= 0 && this.Rows.Count > 0)
            {
                this.Rows[0].Cells[0].Value = "合计";
                string[] s = my_SumColumns.Split(',');
                int x;
                decimal dSum;
                for (int i = 0; i < s.Length; i++)
                {
                    x = Convert.ToInt32(s[i]);
                    dSum = 0;
                    if (my_fatherCDGV.Columns.Count > x)
                    {
                        for (int n = 0; n < my_fatherCDGV.Rows.Count; n++)
                        {
                            try
                            {
                                dSum += Convert.ToDecimal(my_fatherCDGV.Rows[n].Cells[x].Value);
                            }
                            catch
                            {
                                MessageBox.Show("录入数字有错");
                                my_fatherCDGV.My_FocusCell(x, n);
                                return;
                            }
                        }
                        this.Rows[0].Cells[x].Value = dSum;
                    }
                }
            }            
        }
        
        /// <summary>
        /// 重新计算合计行的宽度和高度
        /// </summary>
        private void RefrashMe()
        {
            if (my_fatherCDGV != null)
            {                
                this.Width = my_fatherCDGV.Width;

                int inVisibleCol = 0;
                foreach (DataGridViewColumn dgvc in this.Columns)
                {
                    if (!dgvc.Visible)
                    {
                        inVisibleCol++;
                    }
                }
                if (this.DisplayedColumnCount(false) == this.Columns.Count - inVisibleCol)
                {//判断是否已显示滚动条                    
                    this.Height = my_fatherCDGV.DefaultCellStyle.Font.Height+5;
                }
                else
                {                    
                    this.Height = my_fatherCDGV.DefaultCellStyle.Font.Height*2+5;
                }
            }
        }

        /// <summary>
        /// 重新设置合计行列宽
        /// </summary>
        private void SetColumnsSize()
        {
            if (this.Columns.Count != my_fatherCDGV.Columns.Count)
            {
                return;
            }
            if (this.Columns.Count > 0)
            {
                for (int i = 0; i < my_fatherCDGV.Columns.Count; i++)
                {        
                    this.Columns[i].Width = my_fatherCDGV.Columns[i].Width;                    
                }
                this.RowHeadersWidth = my_fatherCDGV.RowHeadersWidth;
            }
        }

        /// <summary>
        /// 实例合计行
        /// </summary>
        private void NewColumns()
        {
            if (my_fatherCDGV.Columns.Count > 0 )
            {
                this.Columns.Clear();
                this.Rows.Clear();
                for (int i = 0; i < my_fatherCDGV.Columns.Count; i++)
                {
                    this.Columns.Add(my_fatherCDGV.Columns[i].Name, "");
                    this.Columns[i].Width = my_fatherCDGV.Columns[i].Width;
                    this.Columns[i].Frozen = my_fatherCDGV.Columns[i].Frozen;
                    this.Columns[i].Visible = my_fatherCDGV.Columns[i].Visible;
                    this.Columns[i].DefaultCellStyle.Alignment = my_fatherCDGV.Columns[i].DefaultCellStyle.Alignment;
                }
                this.Rows.Add();
                this.RowHeadersWidth = my_fatherCDGV.RowHeadersWidth;
                SetColumnsSize();
            }
        }

        void fatherCDGV_ColumnWidthChanged(object sender, DataGridViewColumnEventArgs e)
        {
            SetColumnsSize();
            RefrashMe();
        }

        private void InitializeComponent()
        {
            ((System.ComponentModel.ISupportInitialize)(this)).BeginInit();
            this.SuspendLayout();
            // 
            // cls_DataGridViewTotalFoot
            // 
            this.RowTemplate.Height = 23;
            //this.DataError += new System.Windows.Forms.DataGridViewDataErrorEventHandler(this.Cls_DataGridViewTotalFoot_DataError);
            ((System.ComponentModel.ISupportInitialize)(this)).EndInit();
            this.ResumeLayout(false);

        }

        private void cls_DataGridViewTotalFoot_SelectionChanged(object sender, EventArgs e)
        {
            my_fatherCDGV.SelectionChanged -= new EventHandler(my_fatherCDGV_SelectionChanged);
            if (my_fatherCDGV.CurrentRow != null && this.CurrentCell!=null)
            {
                my_fatherCDGV.ClearSelection();
                my_fatherCDGV.Rows[my_fatherCDGV.CurrentRow.Index].Cells[this.CurrentCell.ColumnIndex].Selected = true;
            }
            my_fatherCDGV.SelectionChanged += new EventHandler(my_fatherCDGV_SelectionChanged);
        }

        private void Cls_DataGridViewTotalFoot_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {

        }
    }

}

致快乐写代码的那些年

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值