Do you find yourself often turning to the TemplateField type whenever you need a little bit more flexibility than the BoundField or other standard field types of the GridView can offer? Often markup like this becomes prey to cut and paste mayhem, and nobody likes to refactor that.
Writing your own field type is very simple. For instance, why not change the following:
<asp:GridView
ID="_grid"
runat="server"
AutoGenerateColumns="false">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<%# ((DateTime)Eval("Date")).ToString("dddd dd. MMMM") %>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
into the much more elegant:
<asp:GridView
ID="_grid"
runat="server"
AutoGenerateColumns="false">
<Columns>
<iridescence:DateTimeField DataField="Date" DateTimeFormatString="dddd dd. MMMM" />
</Columns>
</asp:GridView>
with only a few lines of code:
public class DateTimeField : BoundField
{
protected override string FormatDataValue(object dataValue, bool encode)
{
DateTime dt = (DateTime)dataValue;
if (null != this.DateTimeFormatString)
{
return base.FormatDataValue(dt.ToString(this.DateTimeFormatString), encode);
}
else
{
return base.FormatDataValue(dt, encode);
}
}
/// <summary>
/// Gets or sets the format string for the DateTime value
/// </summary>
public string DateTimeFormatString
{
get { return ViewState["DateTimeFormatString"] as string; }
set { ViewState["DateTimeFormatString"] = value; }
}
}
Albeit a very simplistic example (for example, I've added no special support for editing dates in the above field type), in many scenarios that is just what makes these little tricks so great :) If you want to create a more advanced field type, have a look at this MSDN article for instance.