Tuesday, October 21, 2008

mailto: Formatted Email Address in asp.net GridView or DetailsView Column using HyperLink control

I had an email address field in a GridView and I implemented a master detail data display using an asp.net GridView and asp.net DetailsView Controls. So I wished to display the email addresses so that one could directly email someone. I maintained to use a hyperlink and give a try to the old method, in which I added one HyperLinkField field in the columns field of an asp.net GridView, like below.

<asp:HyperLinkField
HeaderText="E-mail"
DataTextField="Email"
DataNavigateUrlFormatString="mailto:{0}"
DataNavigateUrlFields="Email"
/>

But this did not work. Using HyperLink only displays the email address but does not provide the link to mail. They say there are some security reasons associated with ImageField and HyperLink Field in the later version. So I had to go much search and finally I found it. The trick is simple. Add a template field and use a hyperlink control, like the one below.

<asp:TemplateField
HeaderText="E-mail"
SortExpression="Email">


<ItemTemplate>


<asp:HyperLink
ID="HyperLink1"
runat=server
Text='<%# Eval("Email") %>'
NavigateUrl='<%# Eval("Email", "mailto:{0}") %>'
/>


</ItemTemplate>


</asp:TemplateField>

Note: You can place your own Email Data column field in the Eval( "myFiledID") expression.

Happy Programming!!

3 comments:

Anonymous said...

Outstanding! Saved my butt! Thanks!

Anonymous said...

Thank you! I wasn't going to try to figure out how to do this, but now I can say: "Look! It Works!"

Anonymous said...

A quicker way of achieiving the same thing would be to convert the field you initially had into a template field using the "Convert this field into a template field" option in your edit Columns dialog. it does all the leg work for you.

Post a Comment

Hope you liked this post. You can leave your message or you can put your valuable suggestions on this post here. Thanks for the sharing and cooperation!

Popular Posts

Recent Articles