HtmlEncode data in your ASP.NET DataGrid

OK, I didn’t know this, but I found out that a DataGrid BoundColumn will not automatically HtmlEncode your data. So if the data contains HTML entities (e.g. “hello this is a <td>”) your web page will break. Yes, it’s a gotcha if you were expecting otherwise. Heh.

The solution is to make the column a TemplateColumn, and wrap the DataBinder.Eval statement with Server.HtmlEncode. To make a column a TemplateColumn in the design view, open the DataGrid properties, go to the Property Builder, click Columns in the left hand pane, click the column you want in Selected columns, and click “Convert this column into a Template column.” If you’re in the HTML pane, you can just replace the asp:BoundColumn tag with an asp:TemplateColumn tag, like below.

Before:

<asp:BoundColumn DataField="Field1" SortExpression="Field1" HeaderText="Field1"></asp:BoundColumn>

After:

<asp:TemplateColumn SortExpression="Field1" HeaderText="Field1">

<ItemTemplate>
<asp:Label id=Label2 runat="server" Text='<%# Server.HtmlEncode(DataBinder.Eval(Container, "DataItem.Field1").ToString()) %>'></asp:Label>
</ItemTemplate>
</asp:TemplateColumn>

If you converted the column to a template column in the IDE design view, you still need to switch to HTML view and add the Server.HtmlEncode function to the Label, e.g.

Before:

<asp:Label id=Label2 runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.Field1") %>'></asp:Label>

After:

<asp:Label id=Label2 runat="server" Text='<%# Server.HtmlEncode(DataBinder.Eval(Container, "DataItem.Field1").ToString()) %>'></asp:Label>

Note: Blogger doesn’t html encode your posts either. 🙂

2