owner drawn listbox

G

Guest

Hi,

I can't seem to figure out how to dynamically add new items with different
font colors to a listbox. I have followed the ColorListBox example at
http://www.codeproject.com/cs/combobox/colorlistbox.asp which i found very
informative. But in the example all the items that should be added to the
listbox is known when the form is loaded.

What I want to do is add lines (items) to the listbox dynamically trough the
application - for instance when a button is clicked I want to add the text
"CLICKED" with red font color to the LISTBOX. I have no idea how to
accomplish this, so if there are anyone who can help me I would really
apreciate it.

Thanks!
 
M

Morten Wennevik

Hi Petrus,

This piece of code will do what you want.
You don't necessarily need a struct or class containing a color, but it
provides some added possibilities. If you also add a 'public override
ToString(){return Name;} to the struct it will show the items correctly
when there is no OwnerDrawn mode (although there will be no color).

Button b1;
Button b2;
ListBox lb;

private struct ListBoxItem
{
public string Name;
public Color ItemColor;
public ListBoxItem(string s, Color c)
{
Name = s;
ItemColor = c;
}
}

public TestForm()
{
b1 = new Button();
b1.Click += new EventHandler(b1_Click);
this.Controls.Add(b1);

b2 = new Button();
b2.Click += new EventHandler(b2_Click);
b2.Location = new Point(b1.Left + b1.Width + 5, b1.Top);
this.Controls.Add(b2);

lb = new ListBox();
lb.DrawMode = DrawMode.OwnerDrawFixed;
lb.DrawItem += new DrawItemEventHandler(lb_DrawItem);
lb.Location = new Point(b1.Left, b1.Top + b1.Height + 5);
this.Controls.Add(lb);
}


private void b1_Click (object sender, EventArgs e)
{
lb.Items.Add(new ListBoxItem("Clicked", Color.YellowGreen));
}

private void b2_Click (object sender, EventArgs e)
{
lb.Items.Add(new ListBoxItem("Clicked", Color.Salmon));
}

private void lb_DrawItem(object sender, DrawItemEventArgs e)
{
ListBoxItem lbi = (ListBoxItem)lb.Items[e.Index];
SolidBrush b = new SolidBrush(lbi.ItemColor);
// you could also do something like
// if(lb.Items[e.Index].ToString() == "Clicked")
// b = Brushes.Red;
// else
// b = Brushes.Black;

// you can also specify background color, although then you will also
// be responsible for highlighting the background when needed
// e.Graphics.FillRectangle(b, e.Bounds);

e.DrawBackground();
e.Graphics.DrawString(lbi.Name, lb.Font, b, e.Bounds);
b.Dispose();
}
 

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

Top