skip to Main Content

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


  1. Chosen as BEST ANSWER

    I solved it as follows incase anyone has a similar problem:

              <asp:Label ID="lblmyLabel" Text= '<%# Convert.ToDateTime(Eval("myField")) !=  Convert.ToDateTime("01/01/0001") ? Convert.ToDateTime(Eval("myField")).ToString("MM/dd/yyyy") : "" %>'  runat="server" > </asp:Label>  
    

  2. Better to use a helper function than add logic in the markup.

    markup

    <asp:Label ID="lblEvalDate" runat="server" 
        Text='<%# CheckEvalDate(Eval("EvalDate")) %>'>
    </asp:Label>
    

    code-behind

    protected string CheckEvalDate(object dt)
    {
        DateTime evalDate;
        if (dt == DBNull.Value || !DateTime.TryParse(dt.ToString(), out evalDate))
        {
            return string.Empty;
        }
        return evalDate == DateTime.MinValue ?
            string.Empty : evalDate.ToString("M/d/yyyy");
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search