freefaller
freefaller

Reputation: 19963

ASP.NET Label removing spaces

Is this a fault in ASP.NET 4.0, or am I missing something obvious...?

I have a <asp:Repeater> with the following lines within the <ItemTemplate>...

<td><asp:Checkbox runat="server" ID="chkInclude" Checked="true" /></td>
<td>
  <asp:Label runat="server" AssociatedControlID="chkInclude">
    <%#Container.DataItem.FirstName%> <%#Container.DataItem.Surname%></asp:Label>
</td>

This results in the firstname and surname being rendered without a space between...

<td>JoeBlogs</td>

There's a simple solution, which is to concatenate the strings...

<asp:Label runat="server" AssociatedControlID="chkInclude">
  <%#Container.DataItem.FirstName & " " & Container.DataItem.Surname%></asp:Label>

... but I'd like to know why the space is being stripped out of the <asp:Label> when using individual <%#Container%> elements. I can't see an obvious attribute on the control that would suggest this can be overridden.


As pointed out in a now-deleted comment, I could also add &nbsp; between the elements as another work-around... but this would stop it word-wrapping if appropriate.


Further investigation (prompted by @Andrei) shows that...

But have two blocks with single space, and it fails (i.e. no space between).

I also tried removing the AssociatedControlID but that also failed.

Upvotes: 1

Views: 1035

Answers (1)

Adrian Iftode
Adrian Iftode

Reputation: 15683

Every time I want to see how ASP .Net generates the code from the aspx markup I create a compilation error on purpose and then I check Show Complete Compilation Source.

I this case you could write something like

<asp:Label runat="server" AssociatedControlID="chkInclude">
    <%#Container.DataItem.FirstName / 2%> <%#Container.DataItem.Surname%></asp:Label>

Then you will see how ASP .Net parses what's between <asp:Label runat="server" AssociatedControlID="chkInclude"> and </asp:Label>.

ASP .Net thinks here are two types of tokens: static strings and data bound strings. It stores them in two different arrays from which it builds, in this case, the Text property of the label control or it renders the html content in the Render method. The problem you have is that ASP .Net it doesn't consider the space between two data bound strings as a static string so it doesn't put that space in the array with the static strings. Once you add any char between these two data bound strings that becomes a static string, including the spaces.

enter image description here

In this image the blue marked texts are data bound strings and what's between them is a static string.


This happens with DataBoundLiteralControl

Upvotes: 2

Related Questions