在网络上看过很多关于DataGridView合计的设计及源码,普遍都显得太过复杂。
特编写一个简单版的实现。

效果图:
C# DataGridView合计行

实现类:

************************************************
 * 作者:许清明
 * Cnblogs:http://www.cnblogs.com/xvqm00
 * 
*************************************************
*/
using System;
using System.Collections.Generic;
using System.Collections;
using System.Text;
using System.Windows.Forms;

namespace WindowsApplication6
{
    
public class FormHelper
    {
        
#region 添加一行
        
public void AddRow(DataGridView dg, string value)
        {
            
if (dg.Rows.Count > 1)
            {
                DelRow(dg, dg.Rows.Count 
- 1);
            }
            dg.Rows.Add();
            
for (int i = 0; i < dg.Columns.Count; i++)
            {
                dg.Rows[dg.Rows.Count 
- 1].Cells[i].Value = value;
            }
            dg.CurrentCell 
= dg.Rows[dg.Rows.Count - 1].Cells[0];
            TotalRow(dg);
        }
        
#endregion
        
#region 编辑一行
        
public void EditRow(DataGridView dg)
        {
            DelRow(dg, dg.Rows.Count 
- 1);
            TotalRow(dg);  
        }
        
#endregion
        
#region 删除一行
        
public void DelRow(DataGridView dg,int index)
        {
            dg.Rows.Remove(dg.Rows[index]);
        }
        
#endregion
        
#region 合计行
        
public void TotalRow(DataGridView dg)
        {
            dg.Rows.Add();
            DataGridViewRow dgr 
= dg.Rows[dg.Rows.Count - 1];
            dgr.ReadOnly 
= true;
            dgr.DefaultCellStyle.BackColor 
= System.Drawing.Color.Khaki;
            dgr.Cells[
0].Value = "合计";
            
for (int i = 0; i < dg.Rows.Count - 1; i++)
            {
                dgr.Cells[
3].Value = Convert.ToSingle(dgr.Cells[3].Value) + Convert.ToSingle(dg.Rows[i].Cells[3].Value);
            }
        }
        
#endregion
    }
}

 

程序包下载:DataGridView自编写合计行

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-11-14
  • 2021-11-14
  • 2022-01-13
  • 2022-01-28
  • 2022-12-23
猜你喜欢
  • 2021-05-19
  • 2021-12-24
  • 2021-11-04
  • 2021-08-16
  • 2022-12-23
  • 2022-01-26
  • 2022-12-23
相关资源
相似解决方案