Thursday, January 15, 2009

How to use HyperLinks GridView with AutoGenerateColumns="True"

Let's assume for some reason, you want to keep AutoGenerateColumns="true" for your GridView, but you want to show a hyperlink in one or more of your columns as a hyperlink. This should also work if AutoGenerateColumns="false" and want to still use BoundField columns. Another scenario might be you want to have embeded html. In either case, GridView is trying to help you by not allowing html (and javascript) be displayed by default. If you are specifying your own columns you can use the TemplateField, etc, but what do you do you do when you don't have that kind of control until Runtime?

Below is a simple solution. It simply converts the escaped HTML back to raw HTML for the browser to render.

protected void gvResults_RowDataBound(object sender, GridViewRowEventArgs e)
{
  // check if each cell in the row has a hyperlink in it,
  // if it does then unescape the html so that it will render as rawhtml

  if (e.Row.RowType == DataControlRowType.DataRow)
  {
   for (int i = 0; i < e.Row.Cells.Count; i++)
   {
    if (e.Row.Cells[i].Text.ToUpper().Contains("&LT;A"))
    {
     e.Row.Cells[i].Text = Server.HtmlDecode(e.Row.Cells[i].Text);
    }

   }
  }

}

There are a few of things to note here.

This method needs to be hooked up to the RowDataBound event of your GridView.

Once you do that this method will fire for each row of data. The looping is really just looking for cells that hyperlinks in them. We have to search for the escaped version of html instead of the raw html. The ToUpper() method is called since we don't know if the link will be like <A or <a.

If you know what column the hyperlink is in the code could be simplified to something like the following code. In this example, we assume the hyperlink or embeded html is in the second column. 

protected void gvResults_RowDataBound(object sender, GridViewRowEventArgs e)
{
 e.Row.Cells[1].Text = Server.HtmlDecode(e.Row.Cells[1].Text);
}

No comments: