Reputation: 1
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
DateTime dt,dt1;
if (e.Row.RowType == DataControlRowType.DataRow)
{
dt = Convert.ToDateTime(e.Row.Cells[4].Text);
e.Row.Cells[4].Text = dt.Month.ToString() + "/" + dt.Day.ToString() + "/" + dt.Year.ToString();
dt1 = Convert.ToDateTime(e.Row.Cells[5].Text);
e.Row.Cells[5].Text = dt1.Month.ToString() + "/" + dt1.Day.ToString() + "/" + dt1.Year.ToString();
}
}
This is my code and the column with index 5 is a datetime the problem is that it can be NULL so the following error turns up when it is
"String was not recognized as a valid DateTime"
Any Solution Please help??!
thank u!
Upvotes: 0
Views: 3168
Reputation: 251
What about setting the BoundField.DataFormatString and the BoundField.NullDisplayText properties, like:
<asp:GridView ID="BoundFieldExample" runat="server">
<Columns>
<asp:BoundField DataFormatString="{0:d}" NullDisplayText="Not Found" />
</Columns>
</asp:GridView>
The above will display dates in short date string format for the current culture and the text "Not Found" for Null values. See GridView BoundField Class for more information.
Upvotes: 0
Reputation: 8293
Try using DateTime.TryParse instead and only if it returns true run the rest of the code
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
DateTime dt,dt1;
if (e.Row.RowType == DataControlRowType.DataRow)
{
bool success = DateTime.TryParse(e.Row.Cells[4].Text, dt);
if(success)
{
e.Row.Cells[4].Text = dt.Month.ToString() + "/" + dt.Day.ToString() + "/" + dt.Year.ToString();
dt1 = Convert.ToDateTime(e.Row.Cells[5].Text);
e.Row.Cells[5].Text = dt1.Month.ToString() + "/" + dt1.Day.ToString() + "/" + dt1.Year.ToString();
}
}
}
Upvotes: 2
Reputation: 11567
Did you try a simple check?
something like
if (!String.IsNullOrEmpty(e.Row.Cells[4].Text))
e.Row.Cells[4].Text = Convert.ToDateTime(e.Row.Cells[4].Text).ToString("MM/dd/yyyy");
else
e.Row.Cells[4].Text = "-";
Upvotes: 0