Sometimes there is a need to do some action on a field returned from the database and displayed inside a TemplateField inside the DataGrid or GridView columns.
For example, you might have an email address inside your database and you want to set the HREF of the a tag as a link with the "mailto:" appended at the beginning of the field.
I usually use a small helper method, that takes as input the field coming from the databasee and formats for me the display I want. In the example below, I am displaying the full name of the customer or client, as a link to his/her email address.
GridView Example:
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<a href='<%# FormatUrl(Eval("email1").ToString())%>'><%# Eval("fname") %>, <%# Eval("lname") %></a>
</ItemTemplate>
</asp:TemplateField>
As you can see, I am calling a method called FormatUrl with an input the email field we're getting from the database.
DataGrid Example:
<asp:TemplateColumn HeaderText="Name">
<ItemTemplate>
<a href='<%# FormatUrl(Eval("email1").ToString())%>'><%# Eval("fname") %>, <%# Eval("lname") %></a>
</ItemTemplate>
</asp:TemplateColumn>
Now the FormatUrl method is as simple as the following:
public string FormatUrl(string email)
{
return "mailto:" + email;
}
The idea is so simple, we are just calling a heler method, giving it the needed fields to return a formatted string as we want.
Hope this helps,
Regards
Tags: ASP.NET 1.x, ASP.NET 2.0 - General