Formatting Hyperlink field in a c# .net DataGrid

Many times we come across a need where we have a hyperlink column in our Datagrid and we want the display text and href=’…’ properties to be formatted in a particular way.


I have a hyperlink column. The DataText field is mapped to the Email field but on mouse over I want “mailto:[email]?subject=…”. So here the [email] is the actual email data from the email field and i also want to have a subject as query string. The way to do it would be to set the DataTextFormatString attribute as follows:

DataTextFormatString=”<A HREF=’mailto:{0}?subject=Report from VIVEK MEHTA’>{0}</A>”

The reason i’ve put a single quote is because i have spaces in my subject query string. If i don’t use quotes, only the first world ‘Report’  will show up trimmign the rest of the bit.

If you need to concat more than one field than you need to adopt a different approach. Use the DataNavigatURLField and DataNavigateURLFormatString fields. This is because DataNavigatURLField can take more than one datafields as value seperate by comman and then the format string can refer them as {0},{1} etc

Finally, if you need to add an extra field in the grid just to count the records, then just add a template field and put the following code:

<asp:TemplateField HeaderText=”#”>
<%#Container.DataItemIndex + 1 %>

This will basically, grab the DataItemIndex on every item data bound and then increment by one and finally assign the value to the itemtemplate via the container object.

Leave a Reply

Please log in using one of these methods to post your comment: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s