|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
Announcements
Services
Chapters
Feature Zones
|
Note: This is an unedited contribution. If this article is inappropriate,
needs attention or copies someone else's work without reference then please
Report This Article
IntroductionUnlike BoundField, HyperLinkField doesn't have a property named "HtmlEncode" or "UrlEncode", etc. But, it's quite normal when you have to do a "UrlEncode" 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, it will be more common. BackgroundSome of us hope Microsoft will add such a common-used feature in next version of .NET Framework. But it's still a problem in .NET 3.x till now. We learned from a feedback report from Microsoft, Microsoft will do no modification on this due to its policy on backward compatibility between versions of .NET Framework. Till now, the popular way to solve this problem is, to convert the HyperLinkField into a TemplateField, and to use HttpUtility.UrlEncode method to solve it by hand. Because this convertion is not reversible, it may introduce some inconvenience when you have to do some small modifications. Using the codeFollowing code gives you another choice, avoiding convertion into TemplateField and hacking for UrlEncode feature for HyperLinkField:
public static void HyperLinkFieldUrlEncodeHack(GridView gridView) { if (gridView == null) { return; } gridView.RowDataBound += delegate(object sender, GridViewRowEventArgs e) { if (e.Row.RowType != DataControlRowType.DataRow) { return; } for (int i = 0; i < gridView.Columns.Count; i++) { DataControlField field = gridView.Columns[i]; if (field is HyperLinkField) { TableCell td = e.Row.Cells[i]; if (td.Controls.Count > 0 && td.Controls[0] is HyperLink) { HyperLink hyperLink = (HyperLink)td.Controls[0]; HyperLinkField hyperLinkField = (HyperLinkField)field; if (!String.IsNullOrEmpty(hyperLinkField.DataNavigateUrlFormatString)) { string[] dataUrlFields = new string[hyperLinkField.DataNavigateUrlFields.Length]; for (int j = 0; j < dataUrlFields.Length; j++) { object obj = DataBinder.Eval(e.Row.DataItem, hyperLinkField.DataNavigateUrlFields[j]); dataUrlFields[j] = HttpUtility.UrlEncode( (obj == null ? "" : obj.ToString())); } hyperLink.NavigateUrl = String.Format( hyperLinkField.DataNavigateUrlFormatString, dataUrlFields); } } } } }; } You may simply call this method and pass the GridView, which includes the HyperLinkField which needs UrlEncode hacking, as the parameter. It'll be OK! Quite simply, isn't it? Points of InterestJust like the guys left comments after the post, I also opposite Microsoft's strict backward compatibility policy. While different versions of .NET applications can run side-by-side, why give so much attension on it? It's just my opion.
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||