Wednesday, May 28, 2014

How to display text in HTML format in GridView?

I was working on GridView for displaying history of records. I realized that I need to highlight some keywords. I was wondering why GridView is not showing text in HTML format. I had a code like this:
<asp:gridview id="gvHistory" runat="server">
    <columns>
        <asp:boundfield datafield="OldValue" headertext="Old Value"/>
        <asp:boundfield datafield="NewValue" headertext="New Value"/>
        <asp:boundfield datafield="strWhen" headertext="Updated On"/>
        <asp:boundfield datafield="ByWhom" headertext="Updated By"/>
    </columns>
</asp:gridview>

Then I found that GridView has by default HTMLEncode=”True”
HTMLEncode: HTML-encodes a string and returns the encoded string.

HTML encoding makes sure that text is displayed correctly in the browser and not interpreted by the browser as HTML. For example, if a text string contains a less than sign (<) or greater than sign (>), the browser would interpret these characters as the opening or closing bracket of an HTML tag. When the characters are HTML encoded, they are converted to the strings & lt ; and & gt ;, which causes the browser to display the less than sign and greater than sign correctly.

Simple Solution for it is to make "False" to HTMLEncode attribute as follow:
<asp:gridview id="gvHistory" runat="server">
    <columns>
        <asp:boundfield datafield="OldValue" headertext="Old Value" 
HTMLEncode="false"/>
        <asp:boundfield datafield="NewValue" headertext="New Value" 
HTMLEncode="false"/>
        <asp:boundfield datafield="strWhen" headertext="Updated On"/> 
        <asp:boundfield datafield="ByWhom" headertext="Updated By"/> 
    </columns>
</asp:gridview>

By making HTMLEncode attribute to "False", You can allow text in HTML Format.

3 comments:

  1. When would you use HTML in the gridview? What circumstance would be a good example to use this?

    ReplyDelete
    Replies
    1. Sometime you want user attention on particular text, in this case, you have to highlight that part of text with some color or you have to make it BOLD. So that part will be easily recognized by the user.

      Circumstance: In my case, I am showing history. I want to highlight “FieldName”. For example “Lastname:Patel” in Old value, so I want to highlight FieldName which is “Lastname” by making it “BOLD”, so it will be easier to read by the user. Lastname:Patel

      Delete
  2. OK, I see your point. That makes a lot of sense.

    ReplyDelete

React-select is very slow on larger list - Found solution - using react-window

 I had more than 4000 items in searchable dropdownlist. I have used react-select but it was very slow. finally I found complete solution to ...