-1

I wrote a code that add some items to a listbox at runtime, now i can't figure out how to acces to the properties of this items (specifically to the FontSize).

Here there is some code

 for (int i = 0; i < list.Count; i++)
      {
          trainerRoutine Item = list[i];
          routines_lst.Items.Add(Item.name);
      }
  • See http://stackoverflow.com/questions/8835568/listbox-manual-drawitem-big-font-size for a similar question; You can either handle DrawItem or MeasureItem events; you can't do it when adding the item. – dash Apr 08 '12 at 22:07

2 Answers2

2

Very hard to see how a "trainerRoutine" might have anything to do with a FontSize. In general, a ListBox stores objects. You are putting strings into the Items collection by using Item.name. That's troublesome, you can't go back from that string to the original object that easily. And it isn't necessary, just can just add Item. The one thing you have to do is to override Item class' ToString() method, that's what ListBox uses to generate the readable string. So:

class DontKnowWhat {
   // properties and methods
   //...
   public override string ToString() {
      return name;
   }
}

Now you can simply get the original object back from the ListBox.Items collection by casting it to DontKnowWhat.


Just in case you are talking about changing the size of the font for an item, crystal ball interpretation number 2, that requires setting the ListBox's DrawMode property to DrawMode.OwnerDrawVariable. There's a good example of that in the MSDN article.

Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536
  • I think the OP was after how to change the font size of items in the ListBox; unlike ASP.Net, the WinForms (assuming it is WinForms) way of doing it is slightly more convoluted. – dash Apr 08 '12 at 22:25
  • I did't add others details just because they where not usefull. – Daniele Kerberos Apr 08 '12 at 23:21
0

Considering that like ListBox item you add a Item.Name, which I suppose a simple string, I would say that for Font property you shouldn't look inside item but inside the ListBox itself.

Tigran
  • 61,654
  • 8
  • 86
  • 123
  • The point is that i need to have a differet size for each item, is that possible? – Daniele Kerberos Apr 08 '12 at 23:19
  • If you are using `wpf` it is possible, but you need to deal with `item template` and *real* width of the item calculated with `GC.MeasureString` – Tigran Apr 09 '12 at 07:48