views:

285

answers:

2

I have a listview but I would like to add 3 properties (for example one of them is "image") to the listviewitems in it.
I was fine with making a custom class with the 3 properties and just inheriting ListViewItem but now I need to use MultiSelect, so it means doing things like(in For Each loops):

ListView1.SelectedItems.Item(i).Image
don't work because it returns a ListViewItem not my CustomClass.
I could always do :
Ctype(ListView1.selectedItems(i), MyCustomClass).Image

But using that over and over again seems like a waste/wrong way to do it?

+2  A: 

It's not a particularly good idea to subclass ListViewItem just to attach custom attributes to it. The class provides a Tag property for specifically this purpose and you should populate that with your own object instead of subclassing. It might not make a big difference syntax-wise, but it's a better design.

Mehrdad Afshari
but theres only 1 tag, I need an image property, a CustomClass and a string.
Jonathan
Then you should attach an instance of a custom class that holds three properties to the `Tag` property of the `ListViewItem` instance.
Mehrdad Afshari
But if I use tag then do ListviewItem.tag.Image it doesn't show in intellisense(that's what the box is called when you type a full stop right?) suggesting this is not the correct way to do it.
Jonathan
Of course. The type of the `Tag` property is `Object` as it's designed to be able to hold *any* instance. You will have to cast the `Tag` property back to the type you assigned to when you want to use it (similar to what you are doing now with the list view item itself; as I said, it wouldn't make much difference syntax-wise). However, the point is, inheritance should be avoided in favor of composition most of the time. In fact, the `Tag` property is specifically *designed* to remove the need of inheritance for situations like yours.
Mehrdad Afshari
Which puts him right back where he came from.
Hans Passant
@nobugz: In terms of pure syntax, yes, as I said, it won't help but inheritance is usually overused and is a bad idea in many cases (including this).
Mehrdad Afshari
Well I found using the Tag object worked until I needed to access the Listviewitem it belonged to (and I cba with making parent properties) so I'm going with inheritance
Jonathan
A: 

That is simply how it works. ListView can store any kind of ListItem and to get to the properties of your derived cast, you have to cast it. You are doing it correctly.

Craig Wilson