In this article I am going to explain how to set DateTime
format in Gridview’s Boundfiled and Template field column.
Description:
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.
Implementations:
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)
{
if(!IsPostBack)
{
BindGrid();
}
}
private void BindGrid()
{
SqlDataAdapter
adp = new SqlDataAdapter("Select * from
DateFormat",
con);
DataTable
dt = new DataTable();
adp.Fill(dt);
if (dt.Rows.Count > 0)
{
grddate.DataSource = dt;
grddate.DataBind();
}
}
Complete
HTML Markup:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="grddate" runat="server" AutoGenerateColumns="False" CellPadding="4" ForeColor="#333333" GridLines="None">
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
<Columns>
<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">
<ItemTemplate>
<%#Eval("Recdate", "{0:MMMM d,
yyyy}")
%>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Created Date">
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%#Eval("Recdate", "{0:D}") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<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" />
</asp:GridView>
</div>
</form>
</body>
</html>
Result:
No comments:
Post a Comment