Wednesday, November 19, 2008

Display Dates with out time in GridView !









Actually GridView displays date with time only even though you store just date in database say 12/2/2003.

How to overcome this?

Use DataFormatString attribute of BoundField to format your data in your source code while you write bound fields code of GridView.

The below sample shows this:

< asp:BoundField DataField="StartDate" HeaderText="StartDate" DataFormatString="{0:d}" HtmlEncode="false" / >
The result will be shown as below:


You need to set HtmlEncode to false also to achieve only date.Otherwise date will be displayed along with time.
There is another way to achieve the same result.
you will write a query to retrieve data from database and you use SqlDataAdapter for this.

In the above shown GridView , the lines of code written to retrieve data are shown below:

private void GetData()
{
string squery="select projectid,projectname,projectdescp,startdate,enddate,
clientname from project";
da = new SqlDataAdapter(squery, con);
bldr = new SqlCommandBuilder(da);
ds = new DataSet();
da.Fill(ds, "Project");
GVProject.DataSource = ds.Tables["Project"];
GVProject.DataBind();
}

Instead of above query replace squery as shown below:

string squery=select projectid,projectname,projectdescp,convert(varchar,startdate,101) as startdate,convert(varchar,enddate,101) as enddate,clientname from project.

1 comment:

Jimmy said...
This comment has been removed by a blog administrator.