-1

我有这个表单应用程序项目。我上传了销售领域的快照。有两个datagridview。底部datagirdview包含TAX details. 包含底部datagrid来自database except “Amount” column。用户提供或自动计算的金额列值。我写一个代码。当我尝试执行时,它显示错误。Index was out of range. Must be non-negative and less than the size of the collection.Parameter name: index. 我该如何解决?

折断::

在此处输入图像描述

这是代码:

        private void dgvSalesFooterAdd_CellStateChanged(object sender, DataGridViewCellStateChangedEventArgs e)
        {
            decimal Total = 0;

            decimal a=Convert.ToDecimal(lblTotalAdd.Text);
            for (int i = 0; i <dgvSalesFooterAdd.Rows.Count ; i++)
            {

                dgvSalesFooterAdd.Rows[i].Cells[4].Value = a + (a * (Convert.ToDecimal(dgvSalesFooterAdd.Rows[i].Cells[3].Value)/100));

                Total += Convert.ToDecimal(dgvSalesFooterAdd.Rows[i].Cells[4].Value);
            }
            lblFinalTotalAdd.Text = Total.ToString();
        }

[注意:错误

dgvSalesFooterAdd.Rows[i].Cells[4].Value = a + (a * (Convert.ToDecimal(dgvSalesFooterAdd.Rows[i].Cells[3].Value)/100));
Total += Convert.ToDecimal(dgvSalesFooterAdd.Rows[i].Cells[4].Value); 

这两条线。]

4

2 回答 2

0

当在i. 您必须将行数减少 1。这将告诉循环仅计算由值填充的行。换行

int i = 0; i <dgvSalesFooterAdd.Rows.Count

int i = 0; i <dgvSalesFooterAdd.Rows.Count - 1

完整的块将如下所示;

        for (int i = 0; i <dgvSalesFooterAdd.Rows.Count - 1; i++)
        {

            dgvSalesFooterAdd.Rows[i].Cells[4].Value = a + (a * (Convert.ToDecimal(dgvSalesFooterAdd.Rows[i].Cells[3].Value)/100));

            Total += Convert.ToDecimal(dgvSalesFooterAdd.Rows[i].Cells[4].Value);
        }
于 2013-11-08T11:33:19.953 回答
0
  dgvSalesFooterAdd.Rows[i].Cells[4].Value = a + (a *(Convert.ToDecimal(dgvSalesFooterAdd.Rows[i].Cells[3].Value)/100));
Total += Convert.ToDecimal(dgvSalesFooterAdd.Rows[i].Cells[4].Value); 

它将引发异常,因为您正在读取第 4 列的值为空值,因为一旦您离开单元格,cell_value 更改就会起作用...

通过这个链接,它会给你一个更好的画面.. http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.cellvaluechanged.aspx

并尝试你这样的代码..

 void dgvSalesFooterAdd_CurrentCellDirtyStateChanged(object sender,
EventArgs e)
 {
if (dgvSalesFooterAdd.IsCurrentCellDirty)
{
    dgvSalesFooterAdd.CommitEdit(DataGridViewDataErrorContexts.Commit);
}
}

  private void dgvSalesFooterAdd_CellStateChanged(object sender, DataGridViewCellStateChangedEventArgs e)
    {
        decimal Total = 0;

        decimal a=Convert.ToDecimal(lblTotalAdd.Text);
        for (int i = 0; i <dgvSalesFooterAdd.Rows.Count ; i++)
        {

            dgvSalesFooterAdd.Rows[i].Cells[4].Value = a + (a * (Convert.ToDecimal(dgvSalesFooterAdd.Rows[i].Cells[3].Value)/100));

            Total += Convert.ToDecimal(dgvSalesFooterAdd.Rows[i].Cells[4].Value);
        }
        lblFinalTotalAdd.Text = Total.ToString();
    }
于 2013-09-16T09:57:22.887 回答