datagridview单元格之间的自动计算,今天在这个网站上看到的,稍微修改了下,新手有些地方没弄懂~!
原文地址:https://blog.csdn.net/sunferny/article/details/4440722
private void dataGridView1_CellParsing(object sender, DataGridViewCellParsingEventArgs e)
{
if (e.ColumnIndex == 14 || e.ColumnIndex == 15)
{
DataGridViewRow theCurrentRow = this.dataGridView1.CurrentRow;
if (!string.IsNullOrEmpty(theCurrentRow.Cells[14].Value.ToString()))
{
if (!string.IsNullOrEmpty(theCurrentRow.Cells[15].Value.ToString()))
{
int accountA = 0;
int accountB = 0;
if (e.ColumnIndex == 14)
{
accountA = Convert.ToInt32(e.Value.ToString());
}
else
{
accountA = Convert.ToInt32(theCurrentRow.Cells["B01C004"].Value);
}
if (e.ColumnIndex == 15)
{
accountB = Convert.ToInt32(e.Value.ToString());
}
else
{
accountB = Convert.ToInt32(theCurrentRow.Cells["B01C005"].Value);
}
int accountC = accountA + accountB;
theCurrentRow.Cells["B01C006"].Value = accountC;
//强制控件使其工作区无效并立即重绘自己和任何子控件
this.dataGridView1.Refresh();
e.ParsingApplied = true;
}
运行程序可行,但是存在问题是在结束编辑的时候提取出的是修改前的数值,且其中一个数值为空不会计算。把代码放到CellEndEdit事件中,就解决提取修改前的数值问题了。
private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex == 14 || e.ColumnIndex == 15)
{
double accountA = 0;
double accountB = 0;
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
accountA = Convert.ToDouble(dataGridView1.Rows[i].Cells[14].Value);
accountB = Convert.ToDouble(dataGridView1.Rows[i].Cells[15].Value);
double accountC = accountA + accountB;
dataGridView1.Rows[i].Cells[16].Value = accountC;
}
}
}
前提是单元格内不能为空,至少得是0。
————————————————————————————————————————
加上下面的代码在单元格输入空白的时候赋值0,避免单元格计算出错。
if ((string)dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].FormattedValue == "")
{
dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = 0;
}