0

I have a windows form that I am displaying as non-modal dialog. As a result I am calling the overloaded Show(IWin32Window owner) method on that form. Only problem is that one of the parent forms that I want to use here is not accessible in the project. As a result I want to load it using reflection using something like code below.

var frm = Assembly.GetEntryAssembly().GetTypes().Where(f => f.Name == "ParentForm").FirstOrDefault();

However this give following compilation errors.

The best overloaded method match for

'System.Windows.Forms.Form.Show(System.Windows.Forms.IWin32Window)' has some invalid arguments

Argument 1: cannot convert from 'System.Type' to 'System.Windows.Forms.IWin32Window'

Any suggestions on how to achieve this?

crazy novice
  • 1,757
  • 3
  • 14
  • 36
  • With reflection, you're getting the `Type` corresponding to `ParentForm`, not an actual `ParentForm` instance. – Tim S. Nov 21 '13 at 21:51
  • is it possible to get it using reflection? – crazy novice Nov 21 '13 at 21:51
  • 2
    You cannot get instances using reflection. It is used only for discovering a `Type` and related properties – Xenolightning Nov 21 '13 at 21:52
  • 1
    To get what, exactly? An existing instance of it, or a new instance of it? The latter is easy, `Activator.CreateInstance(frm)`. For the former, you need to know how to get a reference to it, it [can't just](http://stackoverflow.com/questions/1433714/c-sharp-reflection-is-it-possible-to-find-an-instance-of-an-object-at-runtime) be done automatically. – Tim S. Nov 21 '13 at 21:52
  • 1
    @Tim: For forms, it can. – Ben Voigt Nov 21 '13 at 21:58

1 Answers1

2

You probably will want to search through the Application.OpenForms collection.

Form f = Application.OpenForms.Where(x => x.GetType().Name == "ParentForm").FirstOrDefault();
Ben Voigt
  • 277,958
  • 43
  • 419
  • 720
  • That's a great idea. By reflection I first searched for the type and then looked for that type in all open forms from the API you mentioned. Problem solved... You are the man!!!!!!!!!!! – crazy novice Nov 21 '13 at 22:15
  • @PaulSnow: I think I would have called `GetType()` on each Form in the collection, and checked the name. Getting the name of the type of each form is a bit less work for .NET than getting the name and other metadata of *every* type. But glad you got it working. – Ben Voigt Nov 21 '13 at 23:39