[英]Calculated Column DataGridView - 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());
}
}
我意识到它看到单元格为null,这是否有解决方法? 请帮助。
谢谢。
您可以使用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());
}
我发现了问题,它正在将行默认值读取为null。 我通过将默认值添加到将数据添加到DataGrid的字符串中来替换默认属性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.