对象引用未设置为移除行上对象的实例

本文关键字:对象 实例 设置 对象引用 | 更新日期: 2024-06-14 10:06:50

当用户从数据网格视图中删除一行时,我有以下代码要用来重新计算总计。

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();
      }
 }

没有任何例外。我做错了什么?

对象引用未设置为移除行上对象的实例

GridSellProducts.Rows[i].Cells[4].Value.ToString() 

如果Value为空,则不能执行ToString()

if (GridSellProducts.Rows[i].Cells[4].Value != null) 
{
    ....