当datagridview单元格为空时,c# LINQ查询显示和异常

本文关键字:查询 LINQ 显示 异常 单元格 datagridview | 更新日期: 2023-09-27 18:05:52

我有一个按钮,代码如下:

private void btnCalculate_Click(object sender, EventArgs e)
{
        lblAvg.Text = String.Format("Average score: {0:F2}",
            (from GridViewRowInfo row in studentGridView.Rows
             where row.Cells[1].Value.ToString() != string.Empty
             select Convert.ToDouble(row.Cells[1].Value)).Average());
}

,如果单元格[1]中至少有一个数字(一个带数字的单元格),则返回异常:

An unhandled exception of type 'System.InvalidOperationException' occurred in System.Core.dll

首先,问题在哪里,其次,在获取值之前是否有更明智的方法来检查,当根本没有值,它是空的或null。

当datagridview单元格为空时,c# LINQ查询显示和异常

在你的"where"部分你应该这样做:

lblAvg.Text = String.Format("Average score: {0:F2}", studentGridView == null ? string.Empty : 
 (from GridViewRowInfo row in studentGridView.Rows
              where row.Cells.Count() > 0 && row.Cells[1].Value.ToString() != string.Empty
             select Convert.ToDouble(row.Cells[1].Value)).Average().ToString());

.Average()之前使用DefaultIfEmpty()扩展方法
在您的例子中,如果不存在rows,则返回0