2

I am writing an web application. I want to check if the dateFrom is null or if dateTo is null. If dateFrom is null, print out dateTo, if dateTo is null, then print out dateFrom. If both of then exist, then print out the formation such as 12/3/2015 - 12/3/2015. I have most of the code working, but I cannot figureout how to handle the null date. It keep giving me this exception

String was not recognized as a valid DateTime

Here is my code

public DataSet SearchTimingReq()
{
    DateTime effectDateFrom, effectDateTo;
    DataSet ds = someDataSet();    

    if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
    {
        foreach (DataRow row in ds.Tables[0].Rows)
        {

            if (Convert.ToDateTime(row["Effect_Date_To"].ToString()).ToString("dd/MM/yyyy") == DateTime.MinValue.ToString())
            {
                  row["Effective_Period"] = effectDateFrom.ToString("dd/MM/yyyy");
            }

            if (Convert.ToDateTime(row["Effect_Date_From"].ToString()).ToString("dd/MM/yyyy") == DateTime.MinValue.ToString())
            {
                  row["Effective_Period"] = effectDateTo.ToString("dd/MM/yyyy");
            }

            if (effectDateTo != DateTime.MinValue && effectDateFrom == DateTime.MinValue)
            {
                  row["Effective_Period"] = Convert.ToDateTime(row["Effect_Date_From"].ToString()).ToString("dd/MM/yyyy") + " - " + Convert.ToDateTime(row["Effect_Date_To"].ToString()).ToString("dd/MM/yyyy");
            }    
        }
    }
}

Updated code

if (!DBNull.Value.Equals(row["Effect_Date_From"]))
{
    row["Effective_Period"] = Convert.ToDateTime(row["Effect_Date_To"].ToString()).ToString("dd/MM/yyyy");
}
if (!DBNull.Value.Equals(row["Effect_Date_To"]))
{
    row["Effective_Period"] = Convert.ToDateTime(row["Effect_Date_From"]).ToString("dd/MM/yyyy");
}

if (DBNull.Value.Equals(row["Effect_Date_To"]) && DBNull.Value.Equals(row["Effect_Date_From"]))
{
    row["Effective_Period"] = Convert.ToDateTime(row["Effect_Date_From"].ToString()).ToString("dd/MM/yyyy") + " - " + Convert.ToDateTime(row["Effect_Date_To"].ToString()).ToString("dd/MM/yyyy");
}
Sergii Zhevzhyk
  • 4,074
  • 22
  • 28
RedRocket
  • 1,643
  • 7
  • 28
  • 51

2 Answers2

3

You can use the code below to check for null values on a datatable's datarows.

if (DBNull.Value.Equals(row["Effect_Date_From"])) 
{
   // null
}
Thanos Markou
  • 2,587
  • 3
  • 25
  • 32
  • Thank you for your reply, I am wondering why it said `Convert.ToDateTime(row["Effect_Date_From"].ToString()).ToString("dd/MM/yyyy")` this line cause the exception? – RedRocket Dec 03 '15 at 10:11
0

You can use DateTime.TryParse to handle invalid DateTime values and also parse the date at the same time.

DateTime d;
if(DateTime.TryParse(row["column"], out d)) 
{
//it's a valid DT
}
else
{
//invalid
}
Chris Davis
  • 433
  • 2
  • 10