About GridView, HyperLinkField, UrlEncode

I suppose you were searching the keywords in the title before entering this page. The problem may be:

In a GridView (ASP.NET 2.0), you want to use a HyperLinkField, but you find it doesn't support UrlEncode, while you are planning to pass some variables via URLs. The bug report shows that Microsoft doesn't have any plan on adding such a property, because their policy on backward compatibility between different version of .net frameworks.

I also made a lot of searching and browsing. The popular way to solve this problem always is, to tranform your HyperLinkField into TemplateField, and do UrlEncode by yourself via HttpUtility.UrlEncode method.

Following codes give you another choice, avoiding such a tranformation, and working for your UrlEncode needs. Just have a try!

 

    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)
                {
                    log.Debug(e.Row.RowType.ToString());
                    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);
                        }
                    }
                }
            }
        };
    }

 

Pleased if you find it useful.

posted on 2008-04-18 20:17  破宝  阅读(230)  评论(0编辑  收藏  举报

导航