How to color listbox items at runtime?

  • Thread starter Thread starter Me
  • Start date Start date
M

Me

Hi all,

I've tried this in various ways a while back unsucessfully, but am having
another stab at it now so I thought I'd go ahead and post the question
while I'm looking into it.

I'm writing a csharp win app and want to color code the items in my
listbox dynamically depending upon the contents of each item.

I'm loading up the list box as follows:

listBox1.DisplayMember = "ID";
listBox1.ValueMember = "MyKey";
listBox1.DataSource = MyDataSet.Tables["MyTable"];

In past tries I've gone down the path of trying to cast the item as
System.Web.UI.WebControls.ListItem and using .Attributes.Add
("style","color:red") without sucess.

I've also gone the path of coding a custom listBox1_DrawItem - which also
didn't work due to a known kb issue that I ended up coming across.

I still feel that there HAS to be a way to do this that I'm missing...
anyone know of a way?

Thanks!
 
Me,

You can't use classes from the System.Web.UI.WebControls namespace as
those are for ASP.NET applications, not windows forms applications, as you
are using.

The way to do this is to custom draw the item. Can you point to the KB
article that you found?
 
Thanks for the reply!

I'm going to have to backpedal a bit... since I posted I started looking
into the problem again.

When I coded the coloring using the ownerdraw technique it did color the
rows correctly. However, the problem that prevented me from using that
solution was that when you ownerdraw a listbox in csharp, the horizontal
scrollbar doesn't work - which is a more important feature to what I'm
doing than the coloring.

ie, if I load a textbox up with a string that's longer than the listbox
width, the horiz scroll bar will pop up when the listbox is setup to use
normal draw, but it will not appear when the listbox is set to ownerdraw.

I saw this behavior myself and then came across these two references
while investigating it. One was from a MS dude who was supposed to be
passing it along to the dev team, but I didn't find a kb reference for
it.


http://groups.google.com/group/microsoft.public.dotnet.languages.csharp/b
rowse_thread/thread/de2052a76145d969/7217513918dbaeb9?lnk=st&q=&rnum=1#
7217513918dbaeb9

http://www.dotnet247.com/247reference/msgs/2/12763.aspx
 
Back
Top