Question : convert to valid DateTime

hi

I tried this but get error, what do I wrong ???



<

asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="False" OnRowDataBound="GridView2_DataBound"


 

DataKeyNames="ServiceID" DataSourceID="SqlDataSource1" RowStyle-BackColor="#CCCCCC">

 

public void GridView2_DataBound(Object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            if (Convert.ToDateTime(e.Row.Cells[0].Text) > DateTime.Now.AddMonths(-3))
            {
                e.Row.Cells[0].Style["background-color"] = "red";
            }
            else if (Convert.ToDateTime(e.Row.Cells[0].Text) > DateTime.Now.AddMonths(-6))
            {
                e.Row.Cells[0].Style["background-color"] = "yellow";
            }
        }
    }

THE ERROR MESSAGE IN THE BROWSER:

String was not recognized as a valid DateTime.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.FormatException: String was not recognized as a valid DateTime.

Source Error:


Line 239:        if (e.Row.RowType == DataControlRowType.DataRow)
Line 240:        {
Line 241:            if (Convert.ToDateTime(e.Row.Cells[0].Text) > DateTime.Now.AddMonths(-3))
Line 242:            {
Line 243:                e.Row.Cells[0].Style["background-color"] = "red";
 


Answer : convert to valid DateTime

>check if the row has data(if not, provide a default value),  and if it does have data, then make sure it can be converted.

What you could do is this:

1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
public void GridView2_DataBound(Object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            DateTime currentRowDate = DateTime.Now; // your default value
            DateTime.TryParse(e.Row.Cells[0].Text, out currentRowDate);
            if (currentRowDate > DateTime.Now.AddMonths(-3))
            {
                e.Row.Cells[0].Style["background-color"] = "red";
            }
            else if (currentRowDate > DateTime.Now.AddMonths(-6))
            {
                e.Row.Cells[0].Style["background-color"] = "yellow";
            }
        }
    }
Random Solutions  
 
programming4us programming4us