About GridView, HyperLinkField, and UrlEncode

Tired of converting HyperLinkFields into TemplateFields in order to solve the UrlEncode issue? This solution is right for you.

Introduction

Unlike BoundField, HyperLinkField doesn't have methods like HtmlEncode or UrlEncode etc. But, it's quite normal when you have to do a "URL encode" processing for a hyperlink's parameter. Such as a person name may contain special characters like '&', etc. For eastern developers in China, Japan, or Korea, this will be more familiar.

Background

Some of us hope Microsoft will add such a commonly-used feature in the next version of the .NET Framework. But it's still a problem in .NET 3.x till now. We learned from a feedback report from Microsoft that Microsoft will do no modification on this due to its policy on backwards compatibility between versions of the .NET Framework. Till now, the popular way to solve this problem is to convert the HyperLinkField into a TemplateField and to use the HttpUtility.UrlEncode method to solve it by hand. Because this conversion is not reversible, it may introduce some inconveniences when you have to do some minor modifications.

Using the Code

The following code gives you another choice, avoiding conversion into a TemplateField and hacking for the UrlEncode feature of the HyperLinkField:

You may simply call this method and pass the GridView, which includes the HyperLinkField which needs the URL Encode hacking, as the parameter. It'll be OK! Quite simple, isn't it?

Points of Interest

Just like the guys who left comments after the post, I also opposite Microsoft's strict backwards compatibility policy. While different versions of .NET applications can run side-by-side, why give so much attention to it? That is just my opinion.

I'm so sorry I don't know what kind of source codes should be added. All codes I want to introduce in this article are present in the article. In this article, I only want to share a small but useful tip.