我有以下代码,当用户从datagridview中删除行时,我想用它来重新计算总数。
private void RemoveRow(object sender, EventArgs e)
{
if (GridSellProducts.CurrentCell.ColumnIndex == 7)
{
if (MessageBox.Show("Are you sure you want to remove the row?", "Confirm", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
GridSellProducts.Rows.Remove(GridSellProducts.CurrentRow);
vatTotalCalculate();
amtTotalCalculate();
}
}
}
private void vatTotalCalculate()
{
decimal vatSum = 0;
decimal vSum = 0;
for (int i = 0; i < GridSellProducts.Rows.Count; ++i)
{
if (GridSellProducts.Rows[i].Cells[4].Value.ToString() != null) <--exception thrown here
{
if (Decimal.TryParse((GridSellProducts.Rows[i].Cells[4].Value.ToString()), out vatSum))
vSum += vatSum;
}
}
txtVATTotal.Text = vSum.ToString();
}
如果(GridSellProducts.Rows[i].Cells[4].Value.ToString() != null)
,该行会抛出异常
}
从
private void ValueChanged(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex == 4)
{
vatTotalCalculate();
}
}
不会抛出异常。我做错了什么?
答案 0 :(得分:2)
GridSellProducts.Rows[i].Cells[4].Value.ToString()
如果Value
为空,则您无法执行ToString()
if (GridSellProducts.Rows[i].Cells[4].Value != null)
{
....