How to update ToolStripStatusLabel Text from a method passing all the controls on the form

3.3k Views Asked by At

I have a method to reset some controls on my form. I'm able to get the method to work except for the ToolStripStatusLabel named "tsStatusLabelInfo". This control is not passed to the resetForm() method.

I believe that it is part of the StatusStrip control but I haven't figure out how to get access to the ToolStripStatusLabel control to update the text.

private void resetButton_Click(object sender, EventArgs e)
{
    Utilities.resetForm(this);
}

public static void resetForm(Control form)
{
    foreach(Control c in GetOffSprings(form))
    {
        if (c.Name == "folderTextBox")
        {
            ((TextBox)c).Clear();
        }
        else if (c.Name == "mfrListTextBox")
        {
            ((RichTextBox)c).Clear();
        }
        else if (c.Name == "mfrListDataGridView")
        {
            ((DataGridView)c).DataSource = null;
        }
        else if (c.Name == "onlyRadioButton")
        {
            ((RadioButton)c).Checked = true;
        }
        else if (c.Name == "usRadioButton")
        {
            ((RadioButton)c).Checked = true;
        }
        else if (c.Name == "otherYearsCheckedListBox")
        {
            ((CheckedListBox)c).SetItemCheckState(0, CheckState.Unchecked);
            ((CheckedListBox)c).SetItemCheckState(1, CheckState.Unchecked);
        }
        else if (c.Name == "yearComboBox")
        {
            ((ComboBox)c).Text = string.Empty;
        }
        else if (c.Name == "tsStatusLabelInfo")
        {
            //Control never pass
        }
        else if (c.Name == "statusStrip1")
        {
            // Exception:Object reference not set to an instance of an object
            ((StatusStrip)c).Controls["tsStatusLabelInfo"].Text = string.Empty;
        }
    }
}

//Loop through the control recursively getting all child controls
public static IEnumerable<Control> GetOffSprings(this Control @this)
{
    foreach(Control child in @this.Controls)
    {
        yield return child;

        //MessageBox.Show(child.Name);

        foreach (var offspring in GetOffSprings(child))
        {
            yield return offspring;
        }
    }
}
1

There are 1 best solutions below

1
On BEST ANSWER

It is because of this: https://msdn.microsoft.com/en-us/library/system.windows.forms.toolstrip.controls(v=vs.110).aspx

The Controls collection is not used on the ToolStrip and ToolStripContainer. You should use Items instead: https://msdn.microsoft.com/en-us/library/system.windows.forms.toolstrip.items(v=vs.110).aspx

The items on the tool strip are not Control objects. They are ToolStripItem objects. Looping recursively through the Controls collection will not give you access to these items.