Monday, July 13, 2009

ASP.NET GridView - Format Template column data using format strings and Custom Methods

This article contains GridView template column formatting through Data Format String, ternary operator blocks and custom methods.

Using Format String
Date time


<itemtemplate>
<asp:Label ID="lblDOB" runat="server" Text='<%# Eval("DOB","{0:d}") %>'></asp:Label>
</itemtemplate>
</asp:TemplateField>

For Long Date,

<itemtemplate>
<asp:Label ID="Label8" runat="server" Text='<%# Eval("DOB","{0:d}") %>'></asp:Label>
</itemtemplate>
</asp:TemplateField>

Using ternary operator

<ItemTemplate>
<asp:Image
ID="ImageOpenPending" runat="server"
ImageUrl='<%# Convert.ToInt32(Eval("StateId")) == 1 ? "~/images/icons/DashBoard_Green_Bullet.gif" : "~/images/icons/DashBoard_Red_Bullet.gif" %>' />

<asp:HyperLink ID="HyperLinkWorkOrderSummery" runat="server"
NavigateUrl='<%# "~/AuthUser/WorkOrder_Main.aspx?Id=" + HttpUtility.UrlEncode(DataBinder.Eval(Container.DataItem,"Id").ToString()) + "&mode=View" %>' > <%#Convert.ToDateTime(Eval("StartDate")).ToShortDateString().ToString() + " ," %>
</asp:HyperLink>
</ItemTemplate>

Using a code behind custom method



<ItemTemplate>
<asp:Label ID="LabelPublicComment" runat="server" ToolTip='<%# Eval("PublicComment") %>'
Text='<%# FormatName(DataBinder.Eval(Container.DataItem, "PublicComment")).ToString() %>'>
</asp:Label>
</ItemTemplate>


Write this method in code behind

protected string FormatName(object description)
{
string desc = Convert.ToString(description);
if (desc.Length > 25)
return desc.Substring(0, 25) + "..";
else
return desc;
}

0 comments: