Search code examples
vb.netif-statementlistboxtabcontrollistboxitem

How to know if the item of a TabControl is a listbox?


I was thinking on something like:

If TabControl1.Controls.Item(1) = ListBox Then

End If

Anyway to get if the item is a ListBox or a Button or something like that ?


Solution

  • There are two obvious ways can test the class of an Object.

    If you want to know if the object is literally a ListBox, and nothing else, you can do:

    If myObject.GetType() = GetType(ListBox) Then
    

    If you want to know if the object is a ListBox or is inheriting from ListBox at some point (I often use this form since a lot of the controls I use at work are wrapped into proprietary class):

    If TypeOf myObject Is ListBox Then
    

    There's not a "better method" between the two, it depends on what you're doing and what you need to know.

    Now, in your specific case, there's something important that G3nt_M3caj pointed out: all the controls in the TabControl1.Controls collection will be of the TabPage class. You probably want to test a control from a specific TabPage, so you'll have to find it through your stuff, making sure that you don't create instability with nullPointerExceptions or the like. I gave you the mean to test your objects, but you'll still have to apply these tools to your current situation (which I have not enough info about to help much).