Skip to content
Advertisement

Entity Framework – Formating SQL Time(7) column in Gridview

I have seen many examples of how to populate a grid view using Entity Framework. However, I am struggling to figure out how to manipulate the data before populating the results to the grid view. The only other way I have found to work is to create a SQL Stored Proc and do the formatting there. However, looking for a solution that I can read directly from the table without the need of a Stored Procedure.

I basically have a simple grid view with two columns (Day, Time) with data that looks like this:

When populating this data using Entity Framework, the times are in 24 HR format. I would like them to be shown in 12 HR format.

Here is my current code.

try
{
    using (DemoEntities context = new DemoEntities())
    {
        grdMonday.DataSource = context.TimeSlots.Where(t => t.numericDay == 2).ToList();
        grdMonday.DataBind();
    }
}
catch (Exception ex)
{
    var errMsg = ex.Message;
}

Advertisement

Answer

For anyone with a similar issue, here is the code for how I achieved the desired results. The data from the DB was in SQL TIME(7) format. So I had to convert to a datetime first, in order to format the string correctly.

GridView:

<asp:GridView runat="server" ID="grdMonday" CssClass="table" AutoGenerateColumns="false">
      <Columns>
          <asp:BoundField DataField="day" HeaderText="Day Name" />
          <asp:TemplateField HeaderText="Time">
              <ItemTemplate>
                  <asp:Label runat="server" Text='<%# FormatTime(Eval("time")) %>'></asp:Label>
              </ItemTemplate>
          </asp:TemplateField>
       </Columns>
       <EmptyDataTemplate>
            No Times Found.
       </EmptyDataTemplate>
 </asp:GridView>

Code Behind Function:

protected string FormatTime(object timeValue)
{
   if (Convert.IsDBNull(timeValue))
   {
      return "";
   }
   else
   {
      TimeSpan asTime = (TimeSpan)timeValue;
      DateTime asDate = Convert.ToDateTime(asTime.ToString());
      string time = asDate.ToString("%h:mmtt");

      return time;
    }
 }

Result:

enter image description here

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement