计算列DataGridView-C#

计算列DataGridView-C#,c#,datagridview,calculated-columns,C#,Datagridview,Calculated Columns,我试图在DataGridView中获得一个计算列,起初我认为这很简单,但现在我已经挣扎了一个小时。 编辑列时,下面的代码可以正常工作: private void ReceiptDataGrid_CellEndEdit(object sender, DataGridViewCellEventArgs e) { DataGridViewRow RecieptRow = RecieptDataGrid.Rows[e.RowIndex]; RecieptRow.C

我试图在DataGridView中获得一个计算列,起初我认为这很简单,但现在我已经挣扎了一个小时。 编辑列时,下面的代码可以正常工作:

private void ReceiptDataGrid_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{            
    DataGridViewRow RecieptRow = RecieptDataGrid.Rows[e.RowIndex];
    RecieptRow.Cells[4].Value = double.Parse(RecieptRow.Cells[2].Value.ToString()) * double.Parse(RecieptRow.Cells[3].Value.ToString());            
}
但我正在努力使列在添加新行时自动获取其值。 我得到一个NullReferenceException 使用相同代码时出现异常。 我尝试了一个for循环,得到了相同的错误

private void RecieptDataGrid_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
{
   for (int i = 0; i < e.RowCount; i++)
  {
       DataGridViewRow RecieptRow = RecieptDataGrid.Rows[e.RowIndex + i];
      RecieptRow.Cells[4].Value = double.Parse(RecieptRow.Cells[2].Value.ToString()) * double.Parse(RecieptRow.Cells[3].Value.ToString());         
  }                       
}
private void receiptDataGrid_RowsAdded(对象发送方,DataGridViewRowsAddedEventArgs e)
{
for(int i=0;i
我意识到它看到单元格为空,有没有解决办法? 请帮忙


谢谢。

您可以使用IsNewRow属性检查RecieoRow是否为新行(具有空值):

for (int i = 0; i < e.RowCount; i++)
{
   DataGridViewRow RecieptRow = RecieptDataGrid.Rows[e.RowIndex + i];

   if (RecieptRow.IsNewRow) continue;

   RecieptRow.Cells[4].Value = double.Parse(RecieptRow.Cells[2].Value.ToString()) * double.Parse(RecieptRow.Cells[3].Value.ToString());         
}  
for(int i=0;i
我发现了问题,它将行默认值读取为空。
我通过将默认值添加到向DataGrid添加数据的字符串来替换默认属性。

添加新行时,很有可能所有单元格值都为空,那么如何从这些空值中计算出一些值呢?为了将来参考,您收到的异常名称是
NullReferenceException
。我是C的新手,我理解这个问题,但有解决办法吗?@ArmendImeri这取决于何时添加新行?如果您为某些单元格准备了一些值,只保留一个单元格为空(供以后计算),则RowsAdded的处理程序可能会工作,但我认为您的情况可能不同,通常我们应该仅在其他单元格的值更改时更新单元格,这一点始终正确。