Link to home
Start Free TrialLog in
Avatar of AvinashKN
AvinashKN

asked on

String was not recognized as a valid DateTime

hello all,

I'm getting the error "String was not recognized as a valid DateTime".

Explanation of the code below:

I'm trying to loop through the gridview checking for the current date in the column "Extracted Date" of the gridview. If the date is current date, I'm changing the background color to red. If its not the current date, I'm changing the row to orange.

Any kind of help would be appreciated.
protected void BackColor()
    {
        DateTime dtHH ;
        int intCnt = gvSearchresult.Rows.Count;
        for (int i = 0; i < intCnt; i++)
        {
            GridViewRow gvRow = gvSearchresult.Rows[i];
            string strDate = Convert.ToString(DataBinder.Eval(gvRow.DataItem, "Extracted Date"));
            dtHH = Convert.ToDateTime(strDate);
            if (dtHH == DateTime.Now.Date)
            {
                gvRow.BackColor = System.Drawing.Color.Red;
 
            }
            else
            {
                gvRow.BackColor = System.Drawing.Color.Orange;
            }
        }
    }

Open in new window

Avatar of daveamour
daveamour
Flag of United Kingdom of Great Britain and Northern Ireland image

Can you run this and debug it and see what is in the strDate variable to see what might cause the problem?
Avatar of jmwheeler
jmwheeler

The best way to convert a string to a date when your not sure it will convert is as follows:


DateTime dt;
if(DateTime.TryParse("myStringValue", out dt))
   //Code for successful convert
else
   //Code for conver failure

Open in new window


one possible problem is: are you sure you don't have empty cells?

for the format problem you may want to have a look at the DateTime.ParseExact() method,
your probably is in a format not recognize by the machine and with that method you can specify
the format to be used to convert a string into a date.

ASKER CERTIFIED SOLUTION
Avatar of jmwheeler
jmwheeler

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of sybe
Hmm, so you databind a gridview, in which dates are converted to strings, then you loop through the gridview again, converting all datestrings back to dates to see if they match the current date?

Isn't that a bit too complicated?

Why not have something like

Backcolor="<%=IIF(EVAL("youdate")=new New Date(Now.Year, Now.Month, Now.Day),"Red", "Orange")%>"

in the gridview itself?
Avatar of AvinashKN

ASKER

Not really sure. I'm complete newbie to asp.net  and c# programming and I'm just learning it by playing around with it. I found some tutorials online that did the row color change similar to what I have. That's why I was using it.