我有一个表有一些列,有时会有一个空值。如何检查值是否为空,如果是,则将值设置为空字符串或稍后可以使用的内容?
private DateTime dtDate_Ordered;
private DateTime dtDate_Required;
private DateTime dtDate_Received;
var stringSql = "select * from po where po_num=" + stringPO_NUM;
var Class_Connection = new SQL_Connection();
Class_Connection.cnn.Close();
Class_Connection.cnn.Open();
try
{
var cmd = new SqlCommand(stringSql, Class_Connection.cnn);
SqlDataReader sdr = cmd.ExecuteReader();
while (sdr.Read())
{
dtDate_Ordered = (DateTime)sdr["dateordered"];
dtDate_Required = (DateTime)sdr["daterequired"];
dtDate_Received = (DateTime)sdr["daterecv"];
stringComments = (string)sdr["comments"];
}
}
catch (Exception Ex)
{
Class_Connection.cnn.Close();
throw Ex;
}
Class_Connection.cnn.Close();
RDI_Date_Ordered.SelectedDate = dtDate_Ordered;
RDI_Date_Required.SelectedDate = dtDate_Required;
RDI_Date_Received.SelectedDate = dtDate_Received;
我希望能够在异常处理程序捕获之前处理null值。
答案 0 :(得分:1)
重新定义顶部的日期时间可以为空,例如
private DateTime? dtDate_Ordered;
然后当你从阅读器中分配它时,null不会有问题。
if(sdr["dateordered"]==DbNull.Value)
dtDate_Ordered=null
else
dtDate_Ordered=sdr.GetDateTime(sdr.GetOrdinal("dateordered"))
答案 1 :(得分:1)
在输入值之前,检查每个值以确保它们不为空。
if( sdr["dateordered"] != null)
dtDate_Ordered = (DateTime)sdr["dateordered"];
if( sdr["daterequired"] != null)
dtDate_Required = (DateTime)sdr["daterequired"];
if( sdr["daterecv"] != null)
dtDate_Received = (DateTime)sdr["daterecv"];
stringComments = ( sdr["comments"] == null)? "" : (string)sdr["comments"];