简体   繁体   English

计算列DataGridView-C#

[英]Calculated Column DataGridView - C#

I am trying to get a calculated column in DataGridView, at first I thought it was simple but now I have been struggling for an hour. 我试图在DataGridView中获得一个计算列,起初我以为这很简单,但是现在我已经挣扎了一个小时。 The code below works fine when editing columns: 下面的代码在编辑列时工作正常:

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

But I am struggling to make the column take its value automatically when new rows are added. 但是我很难使添加新行时该列自动取值。 I get a NullReferenceException exception when I use the same code. 当我使用相同的代码时,我得到一个NullReferenceException异常。 I have tried a for loop and got the same error 我尝试了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());         
  }                       
}

I Realize that it sees the cells at nulls about is there a workaround to this? 我意识到它看到单元格为null,这是否有解决方法? Help please. 请帮助。

Thank You. 谢谢。

you could check if your RecieotRow is a new row (with empty values) by using the IsNewRow property: 您可以使用IsNewRow属性检查RecieotRow是否为新行(具有空值):

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

I found the problem, it was reading the row default values as nulls. 我发现了问题,它正在将行默认值读取为null。 I replaced the default properties by adding the default value to the string that adds data to the DataGrid. 我通过将默认值添加到将数据添加到DataGrid的字符串中来替换默认属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM