Search code examples
c#asp.netascx

ASP.Net / C#: Replacing characters in a databound field


In an ascx file I'm presenting data from a databound field like this:

<%# Eval("Description")%>

The data source is bound from code behind.

Sometimes Description has some characters in it that I need to replace. I would love if I could just do something like this:

<%# Replace(Eval("Description"), "a", "b")%>

But of course that's not allowed in a databind operation (<%#).

I don't want to hard code it in code behind because it would be so ugly to extract the field in code behind, maybe extract it to a variable and then output the variable on the ascx page. I'm hoping there is some (probably really easy) way I can do the replace directly on the ascx page.


Solution

  • You can cast the value to a string and handle it like so:

    <%# ((string)Eval("Description")).Replace("a", "b") %>
    

    Or

    <%# ((string)DataBinder.Eval(Container.DataItem, "Description")).Replace("a", "b") %>
    

    Be careful though, because if Description is null you will hit a NullReferenceException. You could do the following to avoid this:

    <%# ((string)Eval("Description") ?? string.Empty).Replace("a", "b") %>