根据此示例,如果列没有值,返回空白(仅限“”),而某些特定字段没有任何字符,如何返回null。
[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 USERID=@USERID"))
{
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 :(得分: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;
答案 1 :(得分:0)
空值将直接来自DB(如果它们存在于该特定行/列的DB中),无论如何要检查数据表中单元格的null /任何其他条件,这里是代码
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;
}
答案 2 :(得分:0)
也许是这样的:
somename1,value1,value2,value3
anothername1,anothervalue1,anothervalue2,anothervalue3
然后:
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;
}
答案 3 :(得分: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;