如何使用c#检查数据表行中的每个值
本文关键字:何使用 检查 数据表 | 更新日期: 2023-09-27 18:12:51
我有两个名为visits
和members
的表,我通过使用以下查询获得数据…
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的空值,就像我上面提到的…
,但我已经失败了检查任何值是空的或不在那一行…
如何检查这一行(row["visit_Logout_DateTime"])中的每个值是否为空
有谁能帮帮我吗?多谢……
与其检查列是否为null
,不如检查列的内容是否为null
。您可以将其与DBNull.Value
:
if (row["visit_Logout_DateTime"] != DBNull.Value)
{
...
}
第一件事-当您不确定值是否为有效对象时,使用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
}
}
}
}
您可以这样使用DateTime.TryParse
:
DateTime date = new DateTime();
if (DateTime.TryParse(row["visit_Logout_DateTime"], out date))
dtlogout = date;
不能对照null
检查row。你应该比较DBNull.Value
。所以,要么输入:
row["visit_Logout_DateTime"] != DBNull.Value
或
!string.IsNullOrEmpty(row["visit_Logout_DateTime"].ToString())
要扩展Kristof的答案,您可以查看扩展方法来整理代码;
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");
注意使用了可空DateTime(尾随?)以便它可以接受空