2017-08-23 178 views
0

我從SQL數據庫讀取數據的方法是ExecuteReader()。 沒有數據的條件,但是HasRow返回true。當我嘗試從閱讀器讀取數據時,我得到了異常: '數據爲空。無法在Null值上調用此方法或屬性。'SqlDataReader沒有數據,但HasRow爲真

SqlDataReader reader = command.ExecuteReader();  
if (reader.HasRows) 
      try 
      { 
       if (reader.Read()) 
       { 
         string aa = reader.GetFieldType(0).Name; // aa returns 'DateTime' 
         dateStart.MinDate = reader.GetDateTime(0); //exception on this line 
         dateEnd.MinDate = reader.GetDateTime(0); 
         dateStart.Value = reader.GetDateTime(0); 
       } 
      } 
      finally 
      { 
       reader.Close(); 
      } 

在此先感謝 Usjwo

+0

有你'檢查值,如果(reader.IsDBNull(0) )'還是三元運算符?如果相應的字段值爲空,則不能使用'GetDateTime'。 –

+0

這可以幫助你----> [數據爲空。此方法或屬性無法在空值上調用](https://stackoverflow.com/questions/24581305/data-is-null-this-method-or-property-cannot-be-called-on-null-values-使用com) – Jixone

+0

非常感謝!有用 :) – Usjwo

回答

0

如果內部零指數SqlDataReader數據包含DBNull,你不能直接從它使用GetDateTime方法,因爲DBNull.Value不能直接轉換爲DateTime。你可以檢查它使用IsDBNull與三元運營商&一個Nullable<DateTime>變量存儲GetDateTime結果分配給其他屬性之前(另見本example):

using (SqlDataReader reader = command.ExecuteReader()) 
{ 
    if (reader.HasRows) 
    { 
     try 
     { 
      while (reader.Read()) 
      { 
       DateTime? minDate = reader.IsDBNull(0) ? (DateTime?)null : reader.GetDateTime(0); 
       if (minDate != null) 
       { 
        dateStart.MinDate = minDate.Value; 
        dateEnd.MinDate = minDate.Value; 
        dateStart.Value = minDate.Value; 
       } 
      } 
     } 
     finally 
     { 
      reader.Close(); 
     } 
    } 
}