No doubt there is an easy solution to this but after serveral hours and failing to find it why not ask the experts? I have a project that contains a meu form (DevExpress NavBar) which is populated from the database. So, I click on an item and I now have a form name which I want to open. Here's the hard part - I can't find any way to iterate through all the forms in my project and .Show the right one, i.e. I can find a forms collection (open forms I can see but not all the forms in my project). I'm just about ready to write a large Case statement to, e.g
Select Case FormName Case "Form1" My.Forms.Form1.Show() Case "Form2" My.Forms.Form2.Show()
but obviously I don't want to do that. What's the best way of doing things?
Cheers, Peter
DirectCast(Activator.CreateInstance(Type.GetType(FormName)), Form).Show()
The Type.GetType() is a method that accepts a string name for the form (i.e.: "MyNamespace.MyFormName") and returns the System.Type for that form. The Activator.CreateInstance() accepts a type and creates a new instance of it through reflection to find the default constructor. The DirectCast just CTypes the returned object as a Form, and Show() is pretty self explanatory.
So, the only change you'll need to make is to change the FormName that you're storing off in DevEx's menu from just "Form1" to "MyNamespace.Form1" so that you will have the full type name of the form you want to show.
Thanks for your input and Ben, thanks for taken the time to explain what was happening in that line of code - very helpful.
All in all this is sooooo depressing - it seems that every time I learn a bit more about .Net it only serves to underline how little I know!!
A follow up - I want to check if a form is already open before I instasiate a new one. I know (thought I knew) how to do this with (and other variations on this theme):
Dim OpenForms As FormCollection OpenForms = Application.OpenForms
' Lets see if the form is already open and, if it is, bring it to the front. For i As Integer = 0 To System.Windows.Forms.Application.OpenForms.Count - 1 If OpenForms(i).Tag.ToString = e.Link.Item.Name.ToString Then OpenForms(i).WindowState = FormWindowState.Normal OpenTheForm = False Exit For End If Next
However, OpenForms.Count always returns zero (even the first time in when just the menu form itself if running). I've been Googling madly to see if there is any reference to the OpenForms.Count being zero and I couldn't find anything - lots of reference to the property in examples of working code - no reference to any problems/caveats.
Any ideas?