Coding RRS feed

  • Question

  • User-1499457942 posted


      I have below code . I check for Null Date in field if it is null or 1753-01-01 then i display value as string.empty . Is there any other better way to do same thing.

     protected void gvwEmployee_RowDataBound(object sender, GridViewRowEventArgs e)
                if (e.Row.RowType == DataControlRowType.DataRow)
                    var dateTime = e.Row.Cells[7].FindControl("lblDate") as Label;
                    if (!string.IsNullOrEmpty(dateTime.Text))
                        DateTime defaultDate = new DateTime(1753, 01, 01);
                        if (DateTime.Parse(dateTime.Text).Date == defaultDate.Date)
                            e.Row.Cells[7].Text = string.Empty;


    Tuesday, December 25, 2018 1:00 PM

All replies

  • User-893317190 posted

    Hi JagjitSingh,

    You could deal with simple logic in  <%# %>.

    Below is my code.

    if (!IsPostBack)
                    DataTable table = new DataTable();
                    table.Columns.Add(new DataColumn("date", typeof(DateTime)));
                    table.Columns.Add(new DataColumn("id", typeof(int)));
                    table.Rows.Add(new DateTime(1721, 02, 05),3);
                    table.Rows.Add(new DateTime(1753, 01, 01),4);
                    table.Rows.Add(new DateTime(1567, 09, 02),5);
                    GridView1.DataSource = table;
      <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" >
                       <asp:BoundField DataField="id" HeaderText="id" />
                    <asp:TemplateField HeaderText="date">
                            <asp:Label ID="Label1" runat="server" Text='<%# Eval("date") as DateTime? ==new DateTime(1753, 01, 01)?"":Eval("date") %>'></asp:Label>

    The result.

    But this way only applies to simple logic, if your logic is complex, it should be written in RowDataBound.

    Or you could write your sql to deal with your problem using case. Case is like if else in c#. 

    As to null, gridview will change null to string.empty automatically.

      when date1 ='1999-02-12' 
      then null
      else date1
      from period

    Best regards,

    Ackerly Xu

    Wednesday, December 26, 2018 2:00 AM
  • User-37275327 posted
     if (DateTime.Parse(dateTime.Text).Date == System.Data.SqlTypes.SqlDateTime.MinValue)
                            e.Row.Cells[7].Text = string.Empty;

    Monday, January 7, 2019 4:44 AM