Rendering HTML Easily within an SPGridView
December 18, 2008 Leave a comment
If you try to create an SPGridView object, and need to include HTML formatted data within that SPGridView, you will quickly notice after viewing it within SharePoint, that the HTML is rendered as straight HTML, and not a link or an image, but, as the HTML code itself.
An easy way around this is to set the HTMLEncode property to false. By default this property is set to true, which will encode your HTML so that it will show up as code, changing <‘s and >’s into < and >, and so on.
Here is an example of this in action.
#region Create Child Controls protected override void CreateChildControls() { try { base.CreateChildControls(); psGrid = new SPGridView(); psGrid.AutoGenerateColumns = false; BoundField colTitle = new BoundField(); colTitle.HeaderText = "Title"; colTitle.HtmlEncode = false; colTitle.DataField = "Title"; this.psGrid.Columns.Add(colTitle); BoundField colDesc = new BoundField(); colDesc.HeaderText = "Description"; colDesc.DataField = "Description"; this.psGrid.Columns.Add(colDesc); this.Controls.Add(this.psGrid); } catch (Exception ex) { Trace.Write(ex); Trace.WriteLine(HttpContext.Current.Request.Url.ToString()); } } #endregion #region Render protected override void Render(HtmlTextWriter writer) { try { using (SPSite site = new SPSite(SPContext.Current.Site.ID)) { using (SPWeb web = site.OpenWeb("/sites/")) { DataTable dt = new DataTable(); dt.Columns.Add("Title"); dt.Columns.Add("Description"); foreach (SPWeb subweb in web.Webs) { DataRow dr = dt.NewRow(); dr["Title"] = "<a href='" + subweb.Url + "'>" + subweb.Title + "</a>"; dr["Description"] = subweb.Description; dt.Rows.Add(dr); } this.psGrid.DataSource = dt; this.psGrid.DataBind(); base.Render(writer); } } } catch (Exception ex) { Trace.Write(ex); Trace.WriteLine(HttpContext.Current.Request.Url.ToString()); } } #endregion