I have a datetime field in a gridview.
I need the date field to be null or empty if the database returns either null, "", or 1/1/0001.
How does one achieve this? I seem to be having a brain freeze.
You can see what I have tried here:
<asp:TemplateField HeaderText="LastEval" ItemStyle-CssClass="gvColumnSmallCss">
<ItemTemplate >
<asp:Label ID="lblmyLabel" Text='<%# Bind("myField","{0:M/d/yyyy}") %>' runat="server" > </asp:Label>
<%-- Text= ' <%# Eval("myField") !=null ? Convert.ToDateTime(Eval("myField")).ToString("MM/dd/yyyy") : "" %>'
--%>
<%-- Text='<%# Bind("myField","{0:M/d/yyyy}") %>'--%>
</ItemTemplate>
C# code:
protected void gv_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
string myField;
myField= (e.Row.FindControl("lblmyField") as Label).Text;
DateTime? myField= null;
_myField = string.IsNullOrEmpty(myField)
? (DateTime?)null
: (DateTime?)DateTime.Parse(myField);
DateTime checkDate = DateTime.Parse("1/1/00001");
if (lastEval == checkDate.ToString() || myField=="")
{
(e.Row.FindControl("lblmyField") as Label).Text = "";
}
}
}
I also tried similar in the RowDataBound
handler method.
2
Answers
I solved it as follows incase anyone has a similar problem:
Better to use a helper function than add logic in the markup.
markup
code-behind