Tuesday, July 18, 2017

How to set DateTime format in Gridview

In this article I am going to explain how to set DateTime format in Gridview’s Boundfiled and Template field column.

In some application we don’t want to show complete date time. In some application we have to show only date or in some cases date with time in different formats. We have DataFormatString options to set date and time.

There are lots of format to set in Gridview. Add a webform to application.

Add namespace
using System.Configuration;
using System.Data.SqlClient;
using System.Data;

C# Code:

SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["connection"].ToString());
    protected void Page_Load(object sender, EventArgs e)
    private void BindGrid()
        SqlDataAdapter adp = new SqlDataAdapter("Select * from DateFormat", con);
        DataTable dt = new DataTable();
        if (dt.Rows.Count > 0)
            grddate.DataSource = dt;

 Complete HTML Markup:

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <form id="form1" runat="server">
        <asp:GridView ID="grddate" runat="server" AutoGenerateColumns="False" CellPadding="4" ForeColor="#333333" GridLines="None">
            <AlternatingRowStyle BackColor="White" ForeColor="#284775" />
                <asp:BoundField DataField="Id" HeaderText="Id" />
                <asp:BoundField DataField="Recdate" HeaderText="Created Date" DataFormatString="{0:dd/MM/yyyy HH:MM tt}"/>
                <asp:TemplateField HeaderText="Created Date">
                        <%#Eval("Recdate", "{0:MMMM d, yyyy}") %>
                 <asp:TemplateField HeaderText="Created Date">
                        <asp:Label ID="Label1" runat="server" Text='<%#Eval("Recdate", "{0:D}") %>'></asp:Label>
            <EditRowStyle BackColor="#999999" />
            <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
            <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
            <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
            <RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
            <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
            <SortedAscendingCellStyle BackColor="#E9E7E2" />
            <SortedAscendingHeaderStyle BackColor="#506C8C" />
            <SortedDescendingCellStyle BackColor="#FFFDF8" />
            <SortedDescendingHeaderStyle BackColor="#6F8DAE" />

How to set DateTime format in Gridview

No comments:

Post a Comment