2011-10-28 18 views
0

我有兩個表名爲visitsmembers,我使用下面的查詢獲取數據..如何使用C#中的數據表中的行檢查每一個值

string sql= @"SELECT member_Firstname, member_Lastname, member_Postcode, 
      visit_DateTime, visit_Status, visit_Logout_DateTime, visits.member_Id, visit_AlertMsg 
      FROM members, visits 
      WHERE members.member_Id = visits.member_Id 
      AND members.member_Active LIKE 'y%'"; 

在這裏我剛剛接到visit_DateTime值通過使用一些比較與組合框值

datatable dt = helper.getdata(sql) 
    foreach (DataRow row in dt.Rows) 
    { 
     if (row["visit_Logout_DateTime"] != null) 
     { 
      DateTime dtlogout = DateTime.Parse(row["visit_Logout_DateTime"].ToString()); 
      if (dtlogout != null) 
      { 
      if (cbPeriod.Text == "Today") 
      { 
       newItem.lblTime.Text = dtlogout.ToString("HH':'mm':'ss"); 

      } 
      else 
       newItem.lblTime.Text = dtlogout.ToString("yyyy'-'MM'-'dd' - 'HH':'mm':'ss"); 
      } 
     } 

    } 

,但我得到了錯誤,在這條線DateTime dtlogout = DateTime.Parse(row["visit_Logout_DateTime"].ToString());

錯誤:string was not recognised as valid datetime (because of one value in that row is empty)

"visit_Logout_DateTime"

我已經得到的"visit_Logout_DateTime"這樣的價值觀....

firstname  lastname postcode  visit_Logout_DateTime 
------------- -------- ---------  --------------------- 
rob   peter  hhd344h    
peter   chan  hy78kjk   2011-09-08 12:09:08 
rock   sam  yudufg3746h  2011-08-08 09:08:45 

我已嘗試檢查該visit_Logout_DateTime的空值像我上面提到..

但我已經失敗了,有史以來值是空的或不在該行...

如何在此行中檢查每一個值(行[「visit_Logout_DateTime」])爲空或不

會不會有人請幫我在這傢伙...

許多感謝....

回答

4

而不是檢查,如果該列是null,你應該檢查列的內容是null。你可以做到這一點通過比較DBNull.Value

if (row["visit_Logout_DateTime"] != DBNull.Value) 
{ 
    ... 
} 
+0

謝謝完美....... – rockyashkumar

1

第一件事 - 當您不確定該值是否爲有效對象時,請使用TryParse,而不是Parse來解析值。

爲了檢查所有值,請嘗試以下的代碼示例檢查每個值:

 DataTable dt = new DataTable("MyTable"); 

     foreach (DataRow row in dt.Rows) 
     { 
      foreach (DataColumn column in dt.Columns) 
      { 
       if (row[column] != null) 
       { 
        string value = row[column].ToString(); 
        if (!String.IsNullOrEmpty(value)) 
        { 
         // Do something 
        } 
       } 
      } 
     } 
+0

謝謝...但我需要檢查該行中的每個值是否爲空或空,我已經嘗試過String.IsNullOrEmpty,但我仍然得到相同的錯誤 – rockyashkumar

+0

嘗試使用下面的Kristof的想法解決方案 –

0

您不能檢查行對null。你應該比較DBNull.Value。 所以,要麼去:

row["visit_Logout_DateTime"] != DBNull.Value 

!string.IsNullOrEmpty(row["visit_Logout_DateTime"].ToString()) 
1

您可以使用DateTime.TryParse這樣的:

DateTime date = new DateTime(); 

if (DateTime.TryParse(row["visit_Logout_DateTime"], out date)) 
      dtlogout = date; 
0

要擴大克里斯托夫的答案你可以看看擴展方法都收拾編碼一點;

public static DateTime? GetDate(this DataRow Row, string ColumnName) 
    { 

     object Value = Row[ ColumnName ]; 

     if(Value == DBNull.Value) 
      return null; 
     else 
      return (DateTime)Value; 

    } 

// Repeat for other types, or use a generic version. 
... 

DateTime? dtlogout = row.GetDate("visit_Logout_DateTime"); 

請注意使用Nullable DateTime(拖尾?),以便它可以接受空值。

相關問題