Th...">

ASP.Net/C#: replacing characters in a data field

In an ascx file, I present data from a data field, for example:

<%# Eval("Description")%> 

The data source is bound from the code behind.

Description sometimes contains some characters that I need to replace. I would really like to be able to do something like this:

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

But of course, this is not allowed in the data binding operation (<%#) .

I don’t want to hard code it in the code, because it would be so ugly to extract a field into the code behind, maybe extract it into a variable, and then output the variable on the ascx page. I hope there are some (perhaps very simple) ways that I can do to replace directly on the ascx page.

+4
source share
2 answers

You can pass the value to a string and process it like this:

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

or

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

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

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

You can bind a binding to an anonymous type containing all the necessary information (including this) that is populated from the code - much less ugly than retrieving it into a variable.

0
source

All Articles