Search code examples
c#listboxnumbersownerdrawn

How to set number of items in owner-drawn listbox


I've implemented the MeasureItem and DrawItem methods in my C# owner-drawn-fixed listbox.

Nothing shows up.

Out of desperation, I added three random strings to the Items collection, and THE FIRST THREE OF MY ITEMS SHOWED UP!

This tells me the listbox didn't know there were items. Do I have to add hundreds of dummy items to the Items collection, just to see MY items?? This is dingbatty; there should be a way to TELL the listbox how many items there are -- I just can't find it!

How do you set the number of items in an owner-drawn listbox?

The code:

private void listVersions_MeasureItem (object sender, MeasureItemEventArgs e)
{
    e.ItemHeight = font.Height + 6;
}

private void listVersions_DrawItem (object sender, DrawItemEventArgs e)
{
    if (entries == null)
        return;

    int i = e.Index;

    if (i < 0 || i >= entries.Count)
        return;

    e.Graphics.FillRectangle (new SolidBrush (BackColor), e.Bounds);
    VersionEntry ent = entries[i];
    Rectangle rect = e.Bounds;
    Graphics g = e.Graphics;

    g.DrawString (i.ToString () + "  " + ent.name, font, Brushes.Black, rect.Location);
}

Solution

  • Try making the DataSource of your ListBox your entries collection:

    listVersions.DataSource = entries