简体   繁体   中英

Foreach frmCustomForm in Application.OpenForms

I'm trying to search through open forms looking for specific types of form [for example frmMain ] in Application.OpenForms so I can call a function specific to that form type

    foreach (frmMain mainForm in Application.OpenForms)
    {
        // code stuff
    }

this does things correctly when it finds the correct type of form, but when it tries other types of form, instead of not considering them it tries to pass them, and it says

Unable to cast object of type Project.frmNotMain' to type 'Project.frmMain'.

how do I stop the foreach from trying to pass the wrong forms?

I have tried

    foreach (frmMain mainForm in Application.OpenForms["frmMain"])

and

    foreach (frmMain mainform in Application.OpenForms.OfType<frmMain>)

both don't work because the foreach cannot operate on a 'method group'.

Since OfType<T> is a method (not property ) you should add () when you want to execute it:

  foreach (frmMain mainform in Application.OpenForms.OfType<frmMain>()) {
    // code stuff
  }

In case you have at most one instance of frmMain ("main" usually means "one" - among many a form just one is "main") you can simplify the loop into

  // Either instance of frmMain or null
  frmMain mainform = Application.OpenForms
    .OfType<frmMain>()      
    .FirstOrDefault();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM