DataGrid with date column that is sometimes blank

S

Stephen Walch

A column in my data source is of type DateTime and "no date" is represented
as DateTime(0). How can I get the DataGrid to display the column as blank
(empty string) in the cases where DateTime.Ticks==0 ?

Thanks!

-Steve
 
S

Steven Cheng[MSFT]

Hi Steve,

Thanks for your posting. As for the displaying DateTime value in DataGRid
column according to its Ticks value question you mentioned, I think we
should use a Template Columns instead of the simple BoundColumn. Are you
currently using BoundColunn to display data? The BoundColumn only simpley
display the certain field retrieved from the datasource via field name and
we can do some additional simple formatting. If you have some more complex
code logical to display the data value, I think it's quite easy to use the
Template Column in which we can use databind statement to embeded our
custom defined helper functions. For exmple:

the following datagrid use a Template Column to display a dateTime field
and use a helper function in the codebehind page class to format the output
according to the dateTime value's Ticks:

<asp:DataGrid id="DataGrid1" runat="server">
<Columns>
<asp:TemplateColumn>
<ItemTemplate>
<%# GetFormattedTime((DateTime)DataBinder.Eval(Container.DataItem,
"date")) %>
</ItemTemplate>
</asp:TemplateColumn>
</Columns>
</asp:DataGrid>

protected string GetFormattedTime(DateTime date)
{
if(date.Ticks == 0)
{
return "Empty Time";
}

return date.ToShortTimeString();
}


And here is a certain tech article introduce the Templates in asp.net :

#Understanding Templates in ASP.NET
http://msdn.microsoft.com/msdnmag/issues/02/01/cutting/default.aspx


Hope also helps. Thanks.

Regards,

Steven Cheng
Microsoft Online Support

Get Secure! www.microsoft.com/security
(This posting is provided "AS IS", with no warranties, and confers no
rights.)
 
E

Elton Wang

Hi Steve,

One way to change DataGrid's display text (or format) can
be done in dataGrid_ItemDataBound Event.

As following code

ListItemType itemType = e.Item.ItemType;
if (itemType == ListItemType.Header || itemType ==
ListItemType.Footer || itemType == ListItemType.Separator)
return;

DataRowView drv = (DataRowView)e.Item.DataItem;
TableCell dateCell = (TableCell)e.Item.Controls;

DateTime dateField = (DateTime)drv;

if(dateField.Ticks == 0){
dateCell.Text = "";
}

Hope it's helpful to you.

Elton Wang
(e-mail address removed)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,482
Members
44,901
Latest member
Noble71S45

Latest Threads

Top