[英]C# LINQ query shows and exception when datagridview cell is empty
好吧,我有一個帶有以下代碼的按鈕:
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());
}
如果在cells [1]中至少有一個數字(一個有數字的單元格),則工作正常,但如果沒有,則返回異常:
An unhandled exception of type 'System.InvalidOperationException' occurred in System.Core.dll
所以首先是問題出在哪里,其次是在根本沒有值並且它為空或為空時,在獲取值之前進行更明智的檢查。
在“哪里”部分中,您應該執行以下操作:
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()
擴展方法
在您的情況下,如果不存在行,則返回0
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.