Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

asp.net

ascx

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.

like image 271
doosh Avatar asked Dec 04 '22 12:12

doosh


1 Answers

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") %>
like image 143
Codesleuth Avatar answered Dec 27 '22 05:12

Codesleuth