How to Handle Null Values in a TemplateField ItemTemplateFiled Under: ASP.NET
I’ve been working on some ASP.NET projects lately and encountered something that was easy to solve, and should have been obvious straight off.
I was using a GridView to display some values including some columns that show dates. To edit the dates I wanted to use some controls from the AJAX Control Toolkit, specifically the MaskedEdit to format the input and the pop up Calendar control, so I had to use a TemplateColumn in the GridView and setup the EditTemplate with these controls.
I also wanted to format the date inside of the ItemTemplate to match the format of the other date BoundFields.
Even in ASP.NET 2.0 this was pretty easy, I just setup the template as follows:
<ItemTemplate>
<%# // If DueDate is null returns an empty string, otherwise formats and displays the date properly.
(null == Eval("DueDate")) ? string.Empty : DateTime.Parse(Eval("DueDate").ToString()).ToString("yyyy/MMM/dd") %>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="DueDate" runat="server" Text='<%# Eval("DueDate") %>' />
<tk:CalendarExtender ID="DueDateCalendar" runat="server" SkinID="Calendar" TargetControlID="DueDate" />
<tk:TextBoxWatermarkExtender ID="DueDateWatermark" runat="server" SkinID="DateWatermark" TargetControlID="DueDate" />
<tk:MaskedEditExtender ID="DueDateMaskedEdit" runat="server" SkinID="DateMask" TargetControlID="DueDate" />
</EditItemTemplate>
The biggest thing was checking for null in the Eval statement for the ItemTemplate. I also setup the ObjectDataSource to ConvertEmptyStringsToNull.
- Permalink
- eric
- 6 Dec 2007 4:47 PM
- Comments (0)