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

时间:2013-12-02 08:33:48

标签: c# datagridview

我有以下代码,当用户从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();
      }
 }

不会抛出异常。我做错了什么?

1 个答案:

答案 0 :(得分:2)

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

如果Value为空,则您无法执行ToString()

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