Introduction
This is my first article and it's a very simple one at that. However, I felt that it was necessary to post it because when I need to find an answer to a programming question, I always come to CP first, and then if I can't find my answer here, I hit Google. A few days ago, I needed to do some coloring in a ListBox
on the web. I found that due to a known "bug/feature" by Microsoft, I couldn't do this. (KB Article.)
So, here are the steps to work around this bug in VS.NET 2003.
Creating your ListBox
- First off, you don't need to use the WebControl
ListBox
. Instead, you need to use the HTML Control ListBox
.
- You need to right click on the
ListBox
and select "Run as server control" so that you may use this ListBox
from code behind.
- Set the following properties (optional):
ID
=ColorListBox1
and Size
=8
.
You now have your ListBox
created but it's not very useful yet now, is it? Next, we will load it up with some data and change some colors.
Loading the ListBox with data
I'm not going to do any databinding although you can. This ListBox
now works just like the normal WebControl ListBox
as far as I can tell. Go to your code behind and edit the Page_Load
event. Add the following lines of code:
ColorListBox1.Items.Clear();
ListItem liRed = new ListItem("Red", "Red");
liRed.Attributes.Add("style",
"background-color: RED");
ListItem liBlue = new ListItem("Blue", "Blue");
liBlue.Attributes.Add("style",
"background-color: BLUE");
ListItem liGreen = new ListItem("Green", "Green");
liGreen.Attributes.Add("style",
"background-color: GREEN");
ColorListBox1.Items.AddRange(new ListItem[]{liRed, liBlue, liGreen});
Now you're done. If you view your aspx page, you should now see the same thing as the picture above.
Points of Interest
The only real point of interest is that Microsoft has a KB article about this, and in that article they say this bug is "by design".
History
Version 1.0 - 8/27/2004.