How to use HtmlEncode with TemplateFields, Data Binding, and a GridView
Posted
by Yadyn
on Stack Overflow
See other posts from Stack Overflow
or by Yadyn
Published on 2009-02-04T17:51:41Z
Indexed on
2010/04/10
23:13 UTC
Read the original article
Hit count: 753
I have a GridView bound to an ObjectDataSource. I've got it supporting editing as well, which works just fine. However, I'd like to safely HtmlEncode text that is displayed as we do allow special characters in certain fields. This is a cinch to do with standard BoundFields, as I just set HtmlEncode to true.
But in order to setup validation controls, one needs to use TemplateFields instead. How do I easily add HtmlEncoding to output this way? This is an ASP.NET 2.0 project, so I'm using the newer data binding shortcuts (e.g. Eval
and Bind
).
What I'd like to do is something like the following:
<asp:TemplateField HeaderText="Description">
<EditItemTemplate>
<asp:TextBox ID="TextBoxDescription" runat="server"
Text='<%# System.Web.HttpUtility.HtmlEncode(Bind("Description")) %>'
ValidationGroup="EditItemGrid"
MaxLength="30" />
<asp:Validator ... />
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="LabelDescription" runat="server"
Text='<%# System.Web.HttpUtility.HtmlEncode(Eval("Description")) %>' />
</ItemTemplate>
</asp:TemplateField>
However, when I try it this way, I get the following error:
CS0103: The name 'Bind' does not exist in the current context
© Stack Overflow or respective owner