1

I have a C# WinForms app with a toolstrip button and two MDI ChildForms called "frmMultiCategoryProject" and "frmTiebreaker". Different actions occur in the toolstrip button's Click() event depending on the toolstrip button's Text property.

Here's the code:

    private void tsbtnAddShowTiebreaker_Click(object sender, EventArgs e)
    {
        if (tsbtnAddShowTiebreaker.Text == "Add Tiebreaker" || tsbtnAddShowTiebreaker.Text == "Show Tiebreaker")
        {
            foreach (frmMultiCategoryProject frmamdic in this.MdiChildren)
            {
                frmamdic.SendToBack();
                frmamdic.Hide();
                frmamdic.Visible = false;
            }
            frmTiebreaker frmTB = new frmTiebreaker(Tiebreaker);
            frmTB.MdiParent = this;
            frmTB.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
            frmTB.Dock = DockStyle.Fill;
            frmTB.Show();
            tsbtnCloseProject.Visible = true;
            frmTB.BringToFront();
            tsbtnAddShowTiebreaker.Text = "Hide Tiebreaker";
        }
        else if (tsbtnAddShowTiebreaker.Text == "Hide Tiebreaker")
        {
            string strMdiChildren = "";

            foreach (frmTiebreaker frmTB in this.MdiChildren)    // This is where the InvalidCastException occurs.
            {
                strMdiChildren += frmTB.Name.ToString() + "\r\n";
                this.Tiebreaker = frmTB.Tiebreaker;
                frmTB.Dispose();
            }

            foreach (frmMultiCategoryProject frmamdic in this.MdiChildren)
            {
                frmamdic.BringToFront();
                frmamdic.Show();
            }

            tsbtnAddShowTiebreaker.Text = "Show Tiebreaker";
        }
    }  

And here's the problem (frmMain.cs:line 2359 is the one with the comment):

System.InvalidCastException was unhandled
  HResult=-2147467262
Message=Unable to cast object of type 'Trivia_Author_v20.frmMultiCategoryProject' to type 'Trivia_Author_v20.frmTiebreaker'.
  Source=Trivia Author v20
  StackTrace:
       at Trivia_Author_v20.frmMain.tsbtnAddShowTBIsClicked() in c:\Users\Reuben\Documents\Visual Studio 2013\TRIVIA AUTHOR SUITE V20 PROJECTS 2\TAS v20 frmTB 2\Trivia Author v10 New Approach\frmMain.cs:line 2359
       at Trivia_Author_v20.frmMain.tsbtnAddShowTiebreaker_Click(Object sender, EventArgs e) in c:\Users\Reuben\Documents\Visual Studio 2013\TRIVIA AUTHOR SUITE V20 PROJECTS 2\TAS v20 frmTB 2\Trivia Author v10 New Approach\frmMain.cs:line 2256
       at System.Windows.Forms.ToolStripItem.RaiseEvent(Object key, EventArgs e)
       at System.Windows.Forms.ToolStripButton.OnClick(EventArgs e)
       at System.Windows.Forms.ToolStripItem.HandleClick(EventArgs e)
       at System.Windows.Forms.ToolStripItem.HandleMouseUp(MouseEventArgs e)
       at System.Windows.Forms.ToolStripItem.FireEventInteractive(EventArgs e, ToolStripItemEventType met)
       at System.Windows.Forms.ToolStripItem.FireEvent(EventArgs e, ToolStripItemEventType met)
       at System.Windows.Forms.ToolStrip.OnMouseUp(MouseEventArgs mea)
       at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
       at System.Windows.Forms.Control.WndProc(Message& m)
       at System.Windows.Forms.ScrollableControl.WndProc(Message& m)
       at System.Windows.Forms.ToolStrip.WndProc(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
       at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
       at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
       at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Application.Run(Form mainForm)
       at Trivia_Author_v20.Program.Main(String[] args) in c:\Users\Reuben\Documents\Visual Studio 2013\TRIVIA AUTHOR SUITE V20 PROJECTS 2\TAS v20 frmTB 2\Trivia Author v10 New Approach\Program.cs:line 116
       at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
       at System.AppDomain.nExecuteAssembly(RuntimeAssembly assembly, String[] args)
       at System.Runtime.Hosting.ManifestRunner.Run(Boolean checkAptModel)
       at System.Runtime.Hosting.ManifestRunner.ExecuteAsAssembly()
       at System.Runtime.Hosting.ApplicationActivator.CreateInstance(ActivationContext activationContext, String[] activationCustomData)
       at System.Runtime.Hosting.ApplicationActivator.CreateInstance(ActivationContext activationContext)
       at System.Activator.CreateInstance(ActivationContext activationContext)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssemblyDebugInZone()
       at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()
  InnerException: 

Why can't my code tell which type of form it's dealing with at any moment?

1 Answer 1

5

The foreach loop doesn't filter its items to the type you declare; it just tries to cast, and will throw that exception when it fails.

To filter, use .OfType<T>().

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, SLaks! this question and my prayers have been answered!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.