Search code examples
.nettoolstriptoolstripitem

how to get a list of a toolstrip control inner controls programmatically


I just noticed the hasChildren method doesn't return the various items in a toolstrip, just because its NOT a container I guess.

There is an answer here in SO but it seems to me its far too complicated.

Is there a simple way to iterate through the toolstrip control's controls?


Solution

  • ANSWER:

    I'm getting home with a very simple recursive call! No need for cumbersome extremely complicated 3 pages c# code guys, here is the code snippet I wrote, and it WORKS:

    Create a for each loop to iterate through all form's controls, and within the loop, call this:

    Private Shared Sub recurseTranslateControls(ByVal lang As String, ByVal c As Control)
    
        Dim newtxt as string = getLangItem(c.name, lang)     ' This function performs string translation
                                                             ' Nothing to do with the current post / answer
        ' This will work for "normal" controls
        If newtxt <> "" Then
            c.Text = newtxt                ' Apply the translated text to the control
        End If
    
        If c.HasChildren Then
            For Each co In c.Controls
                    ' This will work for Toolstrip. You should do same for Menustrip etc.
                    If "toolstrip".Contains(co.GetType.Name.ToLower) Then
                    Dim ts As ToolStrip = co             ' Toolstrip doesn't have child controls, but it DOES have ITEMS!
                    For Each itm As ToolStripItem In ts.Items
                        ' No need for recursivity: toolstrip items doesn't have children
                        Call TranslateToolstrip(lang, itm)           ' Apply the translated text to the toolstrip item
                    Next
                Else
                    Call recurseTranslateControls(lang, co)
                End If
            Next
        End If
    
    End Sub
    
    Private Shared Sub TranslateToolstrip(ByVal lang As String, ByVal t As ToolStripItem)
    
        Dim newtxt = getLangItem(t.name, lang)
    
        If newtxt <> "" Then
            t.Text = newtxt
        End If
    
    End Sub
    

    Important remark: One of the reasons for which I have choosen VB and NOT c# is that c# lends to obfuscated, complex, hard to re-read code, and on top of that, c# "so-called" gurus (not the real ones mind you) are so happty to write code that no one can understand.

    Each time I find a complex c# solution to a problem, i do not accept it, and I ALWAYS find some simpler way to do the job. Yes, ALWAYS, ALWAYS...