DropDownList ListItem Rendering  

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
 
K

Karl Seguin [MVP]

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,774
Messages
2,569,598
Members
45,159
Latest member
SweetCalmCBDGummies
Top