Displaying a Formatted Email Addresses in a GridView or DetailsView (The HyperLinkField Doesn't Cut the Mustard!)

Published 02 December 05 05:12 PM | Scott Mitchell

If you have an Email field in a database and want to display this email as a formatted email address - mailto:emailAddress - in a GridView or DetailsView control in ASP.NET 2.0 you might initially reach for the ol' trusty HyperLinkField, setting its DataTextField property to EmailIDColumnName and its DataNavigateUrlFields and DataNavigateUrlFormatString properties to EmailIDColumnName and mailto:{0}, respectively. Doing so won't give you any warning or error message, but when you view the page in a browser you'll find that the email address is displayed, but not as a clickable email address. Boo.

According to ninatang, an ASP.NET Team Member:

This is due to a security change introduced after Beta2 for ImageField and HyperLinkField to remove the src/href if the data was potentially malicious. You can work around this change by using a TemplateField instead.
[Read nina's messageboard post...]

To remedy this, use a TemplateField, as nina suggests. The easiest way to do this is (IMO) is to add the HyperLinkField and configure its properties as I noted above through the Fields dialog box in the Design view (reached by choosing Edit Columns/Fields from the GridView/DetailsView's smart tag), and then click the “Convert this field into a TemplateField” link. Or, if you prefer to do this by hand in the Source view you can use:

<asp:TemplateField>
<ItemTemplate>
<asp:HyperLink runat=”server” Text='<%# Eval(“EmailIDColumnName“) %>' NavigateUrl='<%# Eval("Email", "mailto:{0}") %>' />
</ItemTemplate>
</asp:TemplateField>

Filed under:

Comments

No Comments

Leave a Comment

(required) 
(required) 
(optional)
(required) 

Archives

My Books

  • Teach Yourself ASP.NET 4 in 24 Hours
  • Teach Yourself ASP.NET 3.5 in 24 Hours
  • Teach Yourself ASP.NET 2.0 in 24 Hours
  • ASP.NET Data Web Controls Kick Start
  • ASP.NET: Tips, Tutorials, and Code
  • Designing Active Server Pages
  • Teach Yourself Active Server Pages 3.0 in 21 Days

I am a Microsoft MVP for ASP.NET.

I am an ASPInsider.