How to determine the ToolStripItem actual type from a ToolStripItemsCollection

djack10

New member
Joined
Jul 31, 2011
Messages
1
Programming Experience
10+
I am converting a VB.Net application to C#. Everything else is going great. Except this bit. I have a function which builds menus,sub menus and seperators from a database. It can build a MenuStrip or a ContextMenuStrip which can then be assigned to a form.


This means that menus can be extensive and conpmex but managed outside the application, which I also use as part of my security access model. All menus are controlled from the database externally, it also means I can develop visual tools (Treeviews etc) to manage user menus. The application uses menus extensively which is by design.


Programmatically I want to assign an eventhandler to every item that isnt a dropdown or a seperator


In VB I would do this, (works perfectly)


C#:
Private Sub AddHandlers (ByVal voMenuItems As ToolStripItemCollection)


    For Each oItem in voMenuItems
        If TypeOf(oItem is ToolStripDropDown) then
            if oItem.DropDownItems.Count > 0 then
                AddHandlers(oItem.DropDownItems)
            Else
                AddHandler oItem.Click, AddressOf ToolBarButtonClick
            End If
        End If
    Next


End Sub


Private Sub ToolbarButtonClick(ByVal sender As System.Object, ByVal e As System.EventArgs)


    'Do something


End Sub
but how would I achieve the same in C#


I have to code my loop like this

C#:
    foreach (ToolStripItem oItem in voMenuItems)

Which always returns a ToolStripItem (using either, GetType or typeof), I cannot find any way to determine the type of item (ToolStripDropDown or ToolStripSeperator) that the ToolStripItem actually is, and even then I can't cast to the type that I want e.g.


C#:
    (ToolStripDropDown)oItem.DropDownItems.Count ...

This gives a compile time error


"System.Windows.Forms.ToolStripItem' does not contain a definition for 'DropDownItems' and no extension method 'DropDownItems' accepting a first argument of type 'System.Windows.Forms.ToolStripItem' could be found (are you missing a using directive or an assembly reference?)"
 
You can paste valid VB code into an online automatic code converter, and usually you get the code converted properly, try searching for 'convert vb to c#'. It would help more if you coded VB with Option Strict turned On of course.
By the way, DropDownItems is a property of ToolStripDropDownItem, which ToolStripMenuItem and a few others inherit. .
 
Back
Top Bottom