Hi Sofia
Refer below code
Database
For this example I have used of Northwind database that you can download using the link given below.
Download Northwind Database
HTML
<form id="form1" runat="server">
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" OnRowDataBound="onRowDataBound">
<Columns>
<asp:BoundField DataField="BirthDate" HeaderText="DateTime" />
<asp:TemplateField HeaderText="Date">
<ItemTemplate>
<asp:Label ID="lblDate" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Time">
<ItemTemplate>
<asp:Label ID="lblTime" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</form>
Namespaces
C#
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
VB.Net
Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration
Code
C#
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
BindGrid();
}
}
private void BindGrid()
{
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("SELECT CONVERT(VARCHAR,BirthDate,0) 'BirthDate' FROM Employees", con))
{
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
DataTable dt = new DataTable();
sda.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
}
}
protected void onRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DateTime datetime = Convert.ToDateTime(e.Row.Cells[0].Text);
(e.Row.FindControl("lblDate") as Label).Text = datetime.ToString("MMM d yyyy");
(e.Row.FindControl("lblTime") as Label).Text = datetime.ToString("hh:mmtt");
}
}
VB.Net
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
If Not Me.IsPostBack Then
BindGrid()
End If
End Sub
Private Sub BindGrid()
Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Using con As SqlConnection = New SqlConnection(constr)
Using cmd As SqlCommand = New SqlCommand("SELECT CONVERT(VARCHAR,BirthDate,0) 'BirthDate' FROM Employees", con)
Using sda As SqlDataAdapter = New SqlDataAdapter(cmd)
Dim dt As DataTable = New DataTable()
sda.Fill(dt)
GridView1.DataSource = dt
GridView1.DataBind()
End Using
End Using
End Using
End Sub
Protected Sub onRowDataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs)
If e.Row.RowType = DataControlRowType.DataRow Then
Dim datetime As DateTime = Convert.ToDateTime(e.Row.Cells(0).Text)
(TryCast(e.Row.FindControl("lblDate"), Label)).Text = datetime.ToString("MMM d yyyy")
(TryCast(e.Row.FindControl("lblTime"), Label)).Text = datetime.ToString("hh:mmtt")
End If
End Sub
Screenshot