Welcome to Bilal Haidar [MVP, MCT] Official Blog Sign in | Join | Help

Using Method inside a DataGrid or GridView TemplateField

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") %>,&nbsp;<%# 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") %>,&nbsp;<%# 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

Published Saturday, March 04, 2006 11:55 PM by BilalHaidar [MVP]

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Comments

# re: Using Method inside a DataGrid or GridView TemplateField

good work... :-)
Friday, July 28, 2006 7:41 AM by tt

Leave a Comment

(required) 
required 
(required)