Thursday, March 31, 2011

Adding html in DataTextFormatString

I have a DropDownList populated from a LINQ query. As per the design requirements of this project, I need to append 4 " " to the DDL's ListItem.Text.

It works when I add the ListItems manually like so:

<asp:ListItem Value="NULL">&nsbp;&nsbp;&nsbp;&nsbp;Select One</asp:ListItem>

but not when I DataBind() and use:

DataTextFormatString = "&nsbp;&nsbp;&nsbp;&nsbp;{0}";

Any help is appreciated.

AND: Before someone says something about the HTML code, I had to call it a "&nsbp;" since it wouldn't allow me to use Non-Breaking Space char code.

Thanks!

From stackoverflow
  • The only thing that I can think to do is sub-class the dropdownlist control and override the render method and see if you can't circumvent the trimming that the base dropdownlist control is doing on its items collection.

    If sub-classing is too much work, then use some client side Javascript code to update those items upon page load. This would be a snap with JQuery. I hope that helps.

  • I've had a look at this and I don't think it is possible to get the 'out of the box' dropdownlist control to do what you are wanting it to do.

    The problem is that any text values you bind to the control will automatically be html encoded. This means that '&nbsp;' will always be converted to '&amp;nbsp;'. This happens whether you add the '&nbsp;' to the text values in your data source before binding it to the control or via the DataTextFormatString property.

    I expect this is done to avoid rogue html breaking the control once it is rendered to the page.

    I think James' suggestion of some kind of custom control is probably your best way to get the functionality your looking for.

  • DropDownList ddl = new DropDownList();
    ddl.Items.Add(new ListItem(Server.HtmlDecode("& n b s p;&n b s p ;& n b s p ;&n bs p;abc"), "abc"));
    

    Hope this helps !

    Note : remove the spaces between characters..

0 comments:

Post a Comment