DropDownList ListItem Rendering  

  • Thread starter Thread starter PJ
  • Start date Start date
P

PJ

Is it possible to prevent the drop down list from html encoding the text in
ListItems? I would like to put some spaces to add padding to certain items
with spaces, but when it it rendered asp.net escapes the ampersand. It even
does this for the htmlselect control.

Thx
~PJ
 
You need HtmlDecode the &nbsp. I like to use a utility function:


private void Page_Load(object sender, EventArgs e)
{
ddl.Items.Add("Canada");
ddl.Items.Add(Padding(2) + "Ontario");
ddl.Items.Add(Padding(2) + "Quebec");
ddl.Items.Add(Padding(2) + "PEI");
}


public static string Padding(int count)
{
if (count == 0)
{
return string.Empty;
}
string[] s = new string[count];
for (int i = 0; i < count; ++i)
{
s = "&nbsp;";
}
return HttpUtility.HtmlDecode(string.Join("", s));
}


Or, even better, create a custom server control which you can easily use
like a normal dropdownlist:

public class PaddedDropDownList : DropDownList
{
protected override void Render(HtmlTextWriter writer)
{
foreach (ListItem item in Items)
{
item.Text = item.Text.Replace(" ",
HttpUtility.HtmlDecode("&nbsp;"));
}
base.Render(writer);
}
}


Karl
 
Back
Top