nrtn93
nrtn93

Reputation: 101

Is there any other way to access open forms in C#?

 Application.OpenForms["formname"];

Is there any other way to access an open form. My application doesn't see this form although it is opened. I dont know why.

Upvotes: 3

Views: 4663

Answers (4)

fruggiero
fruggiero

Reputation: 954

Isn't really necessary a name to get an open form. You can get the form you want by index:

Form frm = Application.OpenForms[0] //Will get the main form
Form frm = Application.OpenForms[1] //Will get the first child

Forms in the OpenForms collection are ordered in the same way that you create it

Otherwise, an alternative is to save a reference to the form and then accessing it by this reference.

//Where you want to save the reference:
Form theForm;
//Where you create the form:
myClass.theForm = new MyForm();
//Where you want to get that form:
MessageBox.Show(myClass.theForm.Caption);

(myClass is the class that will hold your reference to the form, supposing you are accessing it from different classes)

(Also, see if you are affected by this: Application.OpenForms.Count = 0 always)

Upvotes: 2

Ian
Ian

Reputation: 30813

I recommend you to firstly debug your code to check what is the Form actual name which you want to load:

foreach (Form form in Application.OpenForms) {
    string name = form.Name; //check out this name!!
    //print, or anything else will do, you only want to get the name
    //note that you should be able to get any form as long as you get its name correct
}

And then, once you know what is wrong with your code, simply do:

Form form = Application.OpenForms[name]; //use the same name as whatever is available according to your debug

To get your form.

To check more on the possible bugs, See Hans Passant's Post

Upvotes: 2

Shaharyar
Shaharyar

Reputation: 12449

To access the form using this property your form must have a Name.

Remember its not the instance name nor the the form Text:

  Form1 f1 = new Form1();    //not "f1" is the "Name"  
  f1.Text = "it is title of the form"; //neither "Text" is the "Name"
  f1.Name= "its the name"; //it is the "Name"

Sample:

frm_myform form1 = new frm_myform(); 
frm_myform.Name = "form1";

Upvotes: 0

M. Schena
M. Schena

Reputation: 2107

You have to instanciate first a Form. after that you have access to it:

Form1 formname = new Form1();
Application.Run(formname);

// access to form by formname.yourproperty

Upvotes: 1

Related Questions