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

2

5

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.

Zenia answered 29/1, 2013 at 15:12 Comment(3)
Of course, C# does not support procedural programming. What's Replace for C#? Maybe a class? Maybe a pencil? What...? Have you tried with string.Replace(Eval....??Spectacle
Yes. In C# .Replace is done like this: string s = "abc".Replace("a","b"), but in this case I can't do Eval("Description").Replace("a", "b") or (string) Eval("Description").Replace("a", "b").Zenia
You can't do that, because the return value of eval will still be object. But what about ((string)Eval("Description")).Replace("a", "b")?Spectacle
J
17

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") %>
Jehial answered 29/1, 2013 at 15:36 Comment(1)
I've run into a similar situation, only I've got a Decimal field and it's giving me an invalid cast error with the above solution. So I modified it a bit and worked: <%# Eval("PRICE").ToString().Replace(",",".") %>Bonanno
H
0

You could databind to an anonymous type containing all of the information you want (including this) which is populated from the codebehind - much less ugly than extracting it to a variable.

Heterophony answered 29/1, 2013 at 15:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.