2017-03-09 104 views
0

如果列中沒有值和根據此示例,某些特定字段沒有任何字符返回空白(僅「」),我如何能返回空值。如果列中沒有值,我該如何返回空值

 [WebMethod] 
     public string HelloWorld() 
     { 
      return "Hello World"; 
     } 

     [WebMethod] 
     public DataTable GetEmployeeInformation(string USERID) 
     { 
      string constr = ConfigurationManager.ConnectionStrings["MyCon"].ConnectionString; 
      using (SqlConnection con = new SqlConnection(constr)) 
      { 
       using (SqlCommand cmd = new SqlCommand("SELECT * FROM VW_NTB_EIM_O365 WHERE [email protected]")) 
       { 
        using (SqlDataAdapter sda = new SqlDataAdapter()) 
        { 
         cmd.Parameters.AddWithValue("@USERID", USERID); 
         cmd.Connection = con; 
         sda.SelectCommand = cmd; 
         using (DataTable dt = new DataTable()) 
         { 
          dt.TableName = "NTB_EIM_O365"; 
          sda.Fill(dt); 
          if (dt == null) 
          { 
           return null; 
          } 

          return dt; 
         } 
        } 
       } 
      } 
     } 
    } 
} 

回答

0

首先確保數據表不爲空,比檢查行

if(dt!=null) 
{ 
    foreach (DataRow dr in dt.Rows) 
    { 
     //Do your code 
    } 
} 
0

的問題是,你在處置返回數據表。

using (DataTable dt = new DataTable()) // <---- using calls the Dispose() 
{ 
    dt.TableName = "NTB_EIM_O365"; 
    sda.Fill(dt); 
    if (dt == null) 
    { 
     return null; 
    } 

    return dt; 
} 

不要使用使用,因爲返回時,實例不應該設置。你的問題有點模糊,但如果我理解正確,這就是你要找的。至少,它會幫助你在路上。

DataTable dt = new DataTable(); 
dt.TableName = "NTB_EIM_O365"; 
sda.Fill(dt); 

if(dt.Rows.Count == 0) 
    return null; 

// check the first row: 
bool allEmpty = true; 

for (int columnIndex = 0; columnIndex < dt.Columns.Count; columnIndex++) 
{ 
    if (!string.IsNullOrEmpty(dt.Rows[0][columnIndex].ToString())) 
    { 
     allEmpty = false; 
     break; 
    } 
} 

if(allEmpty) 
    return null; 

return dt; 
0

Null值將直接來自DB(如果它們存在於DB在特定行/列),總之如果你想檢查空/任何其他條件對數據表中的單元格,這裏是代碼

if(dt != null && dt.Rows.count > 0){ 
     foreach(DataRow dr in dt.Rows) 
       { 
        if (string.IsNullOrWhiteSpace(dr.Field<string>("col"))) 
        { 
         //do something 
         dr["somecol"] = null; 
        } 
        if (dr.Field<string>("somecol") == "someValue") 
        { 
         dr["somecol"] = string.Empty; 
         //do something 
        } 
       } 
} 
else 
{ 
    return null; 
} 
0

也許這樣的事情:

public bool EmptyDataTable(DataTable dt) 
{ 
    if (dt == null || dt.Rows.Count < 1) 
    return true; 

    for (int i = 0; i < dt.Rows.Count; i++) 
    { 
     if (!string.IsNullOrWhiteSpace(dt.Rows[i].Field<string>("columnName"))) 
     { 
      return false; 
     } 
    } 

    return true; 
} 

然後:

if (EmptyDataTable(dt)) 
{ 
    return null; 
} 
0

你可以試試這個

if (dt != null && dt.Rows.Count>0) 
     return dt; 
     else 
     return null; 

OR

if(dt !=null) 
    { 
     if(dt.Rows.Count>0) 
     { 
      return dt; 
     } 
    } 
    return null; 
相關問題