我有一个datagridview,其中列数根据数据库中的数据是动态的。前三列用于显示姓名,姓氏和全名,后三列用于显示其他人的信息。我想为每一行计算前三列和后三列之间的总和,并将总和放入Total
列中。我的结果不正确。
下面是我的代码:
private void DgvPV_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
{
try
{
double Sum = 0;
int countColumn = DgvPV.ColumnCount;
int countRow = DgvPV.RowCount;
int column = countColumn - 4;
for (int i = 0; i < countRow; i++)
{
for (int j = 3; j < column; j++)
{
Sum += Convert.ToDouble(DgvPV.Rows[i].Cells[j].Value.ToString());
DgvPV.Rows[i].Cells["Total"].Value = Sum;
}
}
for (int i = 1; i < DgvPV.RowCount; i++)
{
DgvPV.Rows[i].Cells["Total"].Value = Convert.ToDouble(DgvPV.Rows[i].Cells["Total"].Value.ToString()) - Convert.ToDouble(DgvPV.Rows[i - 1].Cells["Total"].Value.ToString());
}
}
catch (Exception ex)
{
MessageBox.Show("Erreur de chargement des données... " + ex, "ERREUR DE CONNEXION AU SERVEUR", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
}
答案 0 :(得分:2)
您在外部Sum
中对foreach
变量进行了计算之后,却忘记了重置。这应该可以工作:
double Sum = 0;
int countColumn = DgvPV.ColumnCount;
int countRow = DgvPV.RowCount;
int column = countColumn - 4;
for (int i = 0; i < countRow; i++)
{
Sum = 0; // Your bug was right here
for (int j = 3; j < column; j++)
{
Sum += Convert.ToDouble(DgvPV.Rows[i].Cells[j].Value.ToString());
DgvPV.Rows[i].Cells["Total"].Value = Sum;
}
}
for (int i = 1; i < DgvPV.RowCount; i++)
{
DgvPV.Rows[i].Cells["Total"].Value = Convert.ToDouble(DgvPV.Rows[i].Cells["Total"].Value.ToString()) - Convert.ToDouble(DgvPV.Rows[i - 1].Cells["Total"].Value.ToString());
}