Friday, February 24, 2012

Format DataSource data

I have an SQL database with a number of fields, one of which is for storing the date (datetime).
When I insert data into the table, I only supply the date because I don't want or need the time to be listed. However, when I execute a query, the data that shows up in my gridview is (e.g) 13/10/2007 12:00:00 AM.

What I want ti know is, how can I format the datetime when I run the query so that it only shows 13/10/2007?
This is how I'm retrieving the data at the moment:

SqlCommand command = new SqlCommand("SELECT * FROM tblMail", sqlConn);
conn.Open()
SqlDataReader reader = command.ExecuteReader();
dataGrid.DataSource = reader;
dataGrid.DataBind();
conn.close()

In my dataGrid, I have a number of fields that are bound to the data source, such as Date, Name, Address etc etc
Anyway, any ideas on how I can format the SQL DateTime so it only shows the date in my datagrid?

Add the DataFormatString ({0:d} to display only date) to the column you want to format and set the HtmlEncode to False. This is how your formatted column should look

 <asp:GridView ID="GridView1" runat="server"> <Columns> <asp:BoundField DataField="FromDate"DataFormatString="{0:d}" HtmlEncode="False" /> </Columns> </asp:GridView>

Thanks

-Mark post(s) as "Answer" that helped you

|||

Awesome, thanks for that. I had tried the DataFormatString="{0:d}" but it didn't work...I didn't know to use HtmlEncode="False" too.

I actually got it working by adding a template field etc that looked like this:
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="lblDate" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "Date", "{0:dd/MM/yyyy}")%>' />
</ItemTemplate>
</TemplateField>

but that is way too long-winded compared to the alternative.

Thanks :)

No comments:

Post a Comment