2015-11-14 130 views
-3

當gridview綁定並且gridview沒有返回任何數據時,我得到這個錯誤:System.NullReferenceException:對象引用未設置爲對象的實例。如果gridview返回一些數據,那麼一切都可以。我不知道如何解決它,它在該行System.NullReferenceException:未將對象引用設置爲對象的實例

decimal total = dt.AsEnumerable().Sum(r => r.Field<decimal?>("Remaining_Ballance") ?? 0); 

這裏沒有問題 是我的代碼

cmd.Parameters.Clear(); 
      cmd.Connection = con; 
      cmd.Parameters.Add("@ID", SqlDbType.VarChar).Value = myVarr.ToString(); 

      con.Open(); 
      sda.SelectCommand = cmd; 

      sda.Fill(dt); 
      GridView1.DataSource = dt; 
      GridView1.DataBind(); 

      //Calculate Sum and display in Footer Row 
      decimal total = dt.AsEnumerable().Sum(r => r.Field<decimal?>("Remaining_Ballance") ?? 0);  
      GridView1.FooterRow.Cells[11].Text = "Total"; 
      GridView1.FooterRow.Cells[11].HorizontalAlign = HorizontalAlign.Right; 
      GridView1.FooterRow.Cells[12].Text = total.ToString("N2"); 
+0

什麼是你剛剛拼錯的機率'Ballance'錯了嗎? ('Balance') – Jonesopolis

回答

-1

可以包括執行計算之前進行空條件檢查。

cmd.Parameters.Clear(); 
      cmd.Connection = con; 
      cmd.Parameters.Add("@ID", SqlDbType.VarChar).Value = myVarr.ToString(); 

      con.Open(); 
      sda.SelectCommand = cmd; 

      sda.Fill(dt); 
      GridView1.DataSource = dt; 
      GridView1.DataBind(); 

      //Calculate Sum and display in Footer Row 
if(dt !=null) 
{ 
      if(dt.Rows.Count>0) 
{ 
      decimal total = dt.AsEnumerable().Sum(r => r.Field<decimal?>("Remaining_Ballance") ?? 0);  
      GridView1.FooterRow.Cells[11].Text = "Total"; 
      GridView1.FooterRow.Cells[11].HorizontalAlign = HorizontalAlign.Right; 
      GridView1.FooterRow.Cells[12].Text = total.ToString("N2"); 
} 
} 
0

檢查其空

if(dt != null) 
{ 
      decimal total = dt.AsEnumerable().Sum(r => r.Field<decimal?>("Remaining_Ballance") ?? 0);  
      GridView1.FooterRow.Cells[11].Text = "Total"; 
      GridView1.FooterRow.Cells[11].HorizontalAlign = HorizontalAlign.Right; 
      GridView1.FooterRow.Cells[12].Text = total.ToString("N2"); 
} 
else 
{ 
      //do the alternative 
} 
0

System.NullReferenceException: Object reference not set to an instance of an object.

因爲你填寫你的數據表 「DT」,但返回0行那個時候你的DT對象爲null。如果您在返回此錯誤時可以訪問任何空對象。請替換下面的代碼。

Curreent Code

 //Calculate Sum and display in Footer Row 
     decimal total = dt.AsEnumerable().Sum(r => r.Field<decimal?>("Remaining_Ballance") ?? 0);  
     GridView1.FooterRow.Cells[11].Text = "Total"; 
     GridView1.FooterRow.Cells[11].HorizontalAlign = HorizontalAlign.Right; 
     GridView1.FooterRow.Cells[12].Text = total.ToString("N2"); 

New Code

if(dt != null && dt.Rows.Count > 0) 
{ 
     decimal total = dt.AsEnumerable().Sum(r => r.Field<decimal?>("Remaining_Ballance") ?? 0);  
     GridView1.FooterRow.Cells[11].Text = "Total"; 
     GridView1.FooterRow.Cells[11].HorizontalAlign = HorizontalAlign.Right; 
     GridView1.FooterRow.Cells[12].Text = total.ToString("N2"); 
} 
else 
{ 

} 
相關問題