Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieving a DateTime value from a DataRow (C#)

Tags:

How can I get DateTime value in C# from row, the current code is giving me error any help is appreciated, the data is coming in from progress database:

foreach (DataRow r in ds.Tables[0].Rows) {     string prodCode = r["PRD-CDE"].ToString();     statCode = r["STAT"].ToString();     DateTime firstIssueDate = (DateTime)(r["FISS"]);      DateTime endIssueDate = (DateTime)(r["EISS"]);     if(endIssueDate > DateTime.Now)     { /*do some thing...*/}     else {/*user invalid...*/} } 

there are two ways used in getting date convert and pars, thank you all for the help

Final working Code snippet:

foreach (DataRow r in ds.Tables[0].Rows)             {                 string prodCode = r["PRD-CDE"].ToString(),statCode = r["STAT"].ToString();                // r.<DateTime?>("FISS");                 if (r["FISS"] != DBNull.Value)                 {                     DateTime firstIssueDate = Convert.ToDateTime(r["FISS"]);                     if (r["EISS"] != DBNull.Value)                     {                         DateTime endIssueDate = DateTime.Parse(r["EISS"].ToString());                         if (endIssueDate > DateTime.Now)                         { 
like image 468
Developer Avatar asked Jul 09 '09 20:07

Developer


2 Answers

This is just a guess but if the corresponding type in the database is DateTime, could you check if the column is nullable?

If so you may want to do a check r["column"] == DBNull.Value and then pass it to a nullable DateTime? Field.

Or even easier:

row.Field<DateTime?>("column") 

If it isn't then yeah, Convert.ToDateTime() or something else should do it.

EDIT:

I see your final code there but is there any chance you want to do this:

DateTime? firstIssueDate = r.Field<DateTime?>("fiss");  DateTime? endIssueDate = r.Field<DateTime?>("eiss");   if (firstIssueDate.HasValue && endIssueDate.HasValue)  {      firstIssueDate.Value // blah blah      endIssueDate.Value // blah blah  } 
like image 194
Robert Luong Avatar answered Sep 17 '22 16:09

Robert Luong


I would recommend using DateTime.Parse() if the row is returning a string for that index.

 string prodCode = r["PRD-CDE"].ToString(),statCode = r["STAT"].ToString();  DateTime firstIssueDate = DateTime.Parse(r["FISS"].ToString());  DateTime endIssueDate = DateTime.Parse(r["EISS"].ToString()); 

You could also use TryParse depending on your needs.

like image 29
Chris Thompson Avatar answered Sep 17 '22 16:09

Chris Thompson