HTML Formatting: GridView Vs Datagrid Control

A few days ago while working on a project I had a requirement to display the GridView control with one of the columns as a hyperlink column. The AutoGenerateColumns must be set to true since the columns of the GridView were not fixed. Here is the code I used to create links inside the GridView as well as the Datagrid control.

 <h3>GridView</h3>
    <asp:GridView ID="gvCategories" runat="server"
                onrowdatabound="gvCategories_RowDataBound">
    </asp:GridView>
   
    <br />
         
            <br />
    <br />
    <h3>DataGrid</h3>
    <asp:DataGrid ID="dgCategories" runat="server" />


 private void BindData()
        {
            SqlConnection myConnection = new SqlConnection("Server=localhost;Database=Northwind;Trusted_Connection=true");
            SqlDataAdapter ad = new SqlDataAdapter("SELECT TOP 4 * FROM Categories", myConnection);
            DataSet ds = new DataSet();
            ad.Fill(ds);

            foreach (DataRow row in ds.Tables[0].Rows)
            {
                row["CategoryName"] = ("<a href='#'>" + row["CategoryName"] + "</a>");
            }          

            gvCategories.DataSource = ds;
            gvCategories.DataBind();           

            dgCategories.DataSource = ds;
            dgCategories.DataBind();            
        } 

 

The result is shown in the image below:

gridviewdatagriddecoding

As, you can see that the Datagrid displayed the links correctly while the GridView displayed the encoded links. The fix is pretty simple! Simply, override the behavior in the Row_DataBound event of the GridView control as show below:

  protected void gvCategories_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                e.Row.Cells[1].Text = Server.HtmlDecode(e.Row.Cells[1].Text);               
            }
        }

Now, if you run the application again the GridView will be displayed with links and *not* with encoded string.

gridviewdatagriddecoding1

Print | posted @ Thursday, February 21, 2008 5:13 AM

Twitter