Search code examples
c#.netanonymous-methods

How is this throwing an InvalidCastException


The following code snip is throwing an InvalidCastException on the foreach loop :

Unable to cast object of type 'System.Windows.Forms.StatusStrip' to type 'System.Windows.Forms.GroupBox'.

I just dont understand how this is possible.... Then again I'm a noob so its probably something stupid.

     private void doSlide(GroupBox MoveThis)
    {
        //location 12,27
        var t = Task.Factory.StartNew(() =>
            {
                ExecuteSecure(() =>
                    {
                            foreach (GroupBox box in this.Controls)
                            {
                                if (box != MoveThis)
                                {
                                    box.Left = (-1) * box.Width;
                                }
                                else
                                {
                                    do
                                    {
                                        if (box.Left > 12)
                                            box.Left--;
                                        else
                                            box.Left++;
                                    }
                                    while (box.Left != 12);
                                }
                            }

                    });
            });
    }

Here is the code for Execute Secure

private void ExecuteSecure(Action a)
        {
            if (InvokeRequired)
                BeginInvoke(a);
            else a();
        }

Basically I have a form with a fixed size and several group boxes on the form, only 1 of which is visible at any given point. When we need to make a new GroupBox visible we call DoSlide(GroupBox) and specify the groupbox we want to make visible. It is then supposed to move every GroupBox on the form to the location (-Box.Width,27) except for the specified form which gets slide (incremented or decremented box.left) into view.


Solution

  • You want to use

    this.Controls.OfType<GroupBox>()
    

    in your foreach. This.Controls returns all controls, not just GroupBoxes. The OfType<T> extension method filters the collection to the type you specify.