我有这个表单应用程序项目。我上传销售字段的快照。有两个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);
这两个lins。]
答案 0 :(得分:0)
在i
中找不到Row索引时抛出异常。您必须将行数减少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);
}
答案 1 :(得分:-1)
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列的值为null,因为一旦离开单元格,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();
}