在网络上看过很多关于DataGridView合计的设计及源码,普遍都显得太过复杂。
特编写一个简单版的实现。
效果图:
实现类:
FormHelper
/*************************************************
* 作者:许清明
* 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
}
}
/*************************************************
* 作者:许清明
* 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自编写合计行