Is there any other way to access open forms in C#? - 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.

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)

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

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

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";

Related

Proper instatiating a WinForm via string in C#

I am working on a Winforms application that uses base window (e.g. Form1) and many other windows (e.g. Form2, Form3, ...). All of these windows have their property TopLevel set to false, no border and I am placing them in the Form1 when I need them. I am not skilled enough or do not have the brain capacity to solve this issue:
public void ShowForm(string strNewForm) {
var frmNew = Activator.CreateInstance(Type.GetType(strNewForm)) as Form;
frmNew.TopLevel = false;
frmNew.Size = new Size(rctForm.Width, rctForm.Height);
frmNew.Location = new Point(rctForm.X, rctForm.Y);
frmNew.InitializeForm(strActualSection, strActualSubSection);
frmNew.Parent = this;
frmNew.Show();
}
The strNewForm variable contains the name of Form to show. All the methods and properties in each Form can be used as these all are inherited from base class Form. Problem is with InitializeForm() which I use in each form (Form2, Form3, ...) to do various stuff. I know my problem is in this line:
var frmNew = Activator.CreateInstance(Type.GetType(strNewForm)) as Form;
When strNewForm contains string "Form2" and I change as Form to as Form2 it works just fine. I know I need to change it to proper name each time, but I don't know how. I tried to use this:
Type frmType = Type.GetType(strNewForm);
var frmNew = Activator.CreateInstance(Type.GetType(strNewForm)) as frmType;
But it throws an error CS0118: frmType is a variable but is used as a type. I don't know how to solve this, I tried many solutions and I googled for half a day straight and I am still lost. Any insight would be really helpful.
You cannot use a run-time variable to create strongly-typed code.
You have to provide a compile-time type after the as.
If you know it's a Form then all you can do is this:
var frmNew = Activator.CreateInstance(Type.GetType(strNewForm)) as Form;
If you need specific methods or properties then use a custom Form as your base-type and use that in the as.
Why won't you pass a Form object in your ShowForm method?
public void ShowForm(Form newForm)
{
newForm.TopLevel = false;
newForm.Size = new Size(rctForm.Width, rctForm.Height);
newForm.Location = new Point(rctForm.X, rctForm.Y);
newForm.InitializeForm(strActualSection, strActualSubSection);
newForm.Parent = this;
newForm.ShowDialog();
}

How to get form when it is which is not visible?

I want to get form which is open but hidden. I have tried by this. I get the form but in this case form show and hide within fraction of second. If I skip mfrm.Show(), I don't get MailSynchronize form in Application.OpenForms.
MailSynchronize mfrm = new MailSynchronize();
mfrm.Show();
mfrm.Hide();
I get form by following method.
foreach (Form f in Application.OpenForms) //it will return all the open forms
{
if (f.Name == "MailSynchronize")
{
mfrm = (MailSynchronize)f;
break;
}
}
Can anybody please suggest me how to get open form which is hidden by default and I can get in Application.OpenForms?
If I Hide a form, does it exist in Application.OpenForms?
No, unfortunately if you Hide a form, it will not be present in Application.OpenForms
So how can I open an invisible Form? Also I want it to exists in Application.OpenForms.
If you want to open an invisible Form, and you want it want it to exists in Application.OpenForms, you can use this code instead of simply Show():
var f = new MailSynchronize();
f.Opacity = 0;
f.ShowInTaskbar = false;
f.Show();
How to find that form again?
To get the open instance of form you can use Application.OfType<MailSynchronize>()
var f= Application.OpenForms.OfType<MailSynchronize>()
.FirstOrDefault();
When I found it, How to show it again?
f.Opacity = 1;
f.ShowInTaskbar = true;
f.Show();
How to hide it again?
You should not call Hide() to hide the form because it makes the form to get out of Application.OpenForms, instead you should use this way:
f.Opacity = 0;
f.ShowInTaskbar = false;
Is there another way?
Yes, for example you can create an static property in a class, for example in Program.cs this way:
public static MailSynchronize MailSynchronizeInstance { get; set; }
and the first time you want to open your form, you can assign the instance to this property, and then you can use it using Program.MailSynchronizeInstance to show or hide and you don't need to look in Application.OpenForms or perform a workaround.
Also you can make this property in a singletone way.
EDIT
This should work for your specific case now:
this.Opacity = 0;
this.ShowInTaskbar = false;
When you add these 2 codelines in your MailSynchronize constructor the form will start minimized but will not show in your taskbar, which is essentially the effect you were looking for. Also the form will now popup in your Application.OpenForms Collection.
When form initiallize.
MailSynchronize mfrm = new MailSynchronize();
mfrm.Opacity = 0;
mfrm.Show();
mfrm.Hide();
How to find that form again?
foreach (Form f in Application.OpenForms) //it will return all the open forms
{
if (f.Name == "MailSynchronize")
{
mfrm = (MailSynchronize)f;
break;
}
}
When I found it, How to show it again?
mfrm.Opacity = 1;
mfrm.Show();
Hide again by Button.
mfrm.Hide(); //It will not show form in Application.OpenForms if I hide again by mfrm.Opacity = 0;
use f.Visible (return type is bool)
if it returns false, it means form is hidden. If it returns true then form is visible.

C#: set active form, change field on that form

I'm trying to add an item to listBox1 that's on Form4 from Form5. I researched it and found an answer on this site that is supposed to work:
var form = Form.ActiveForm as Form4;
form.listBox1.Items.Add("aaa");
I get a "NullReferenceException". That's the solution I found but I don't even understand why it should work. My instance of Form4 is called formfour and I create like this from the main form:
Form4 formfour = new Form4();
formfour.Show();
The listBox1 modifiers is set to public.
The reason you are getting the NullRefereneException is that your current ActiceForm is not being casted as Form4, that is why you get null in your instance form.
From the question it appears that you have Form4 opened and you want to set that form as active:
You can use Application.OpenForms property and get an instance of Form4 like:
Form4 form = Application.OpenForms["Form4"] as Form4;
if(form != null)
form.Focus();
also if you want to add items to list box on existing form then:
form.listBox1.Items.Add("aaa");
In Form5
Form4 frm4= new Form4();
frm4.listbox.Items.Add("aaa");
// make sure that the listbox on form4 is set to public from its properties
To refresh the form4 use
frm4.refresh();
And for more go through this link

Open form with Form Name in winform appliaction

I want to ask what should i do to open form with the help or class name in winform c#?
I have three different forms
UserManagement
GroupsManagement
LocationManagement
I get permission from database for these three forms
in menu click i fill tag Property with the name of form like this
tsmMain.Tag = item.PermissionName
tsmMain.Click += new EventHandler(tsmMain_Click);
what i want to do is to open form dynamically in button click and to remove these if condition?
Can i do this with reflection or else??
ToolStripMenuItem aa = sender as ToolStripMenuItem;
var tag = aa.Tag;
if (tag == "User Management")
{
UserManagement oUserForm = new UserManagement();
oUserForm.Show();
}
if (tag == "Groups Management")
{
GroupManagement oGroupForm = new GroupManagement();
oGroupForm.Show();
}
You may be able to do something like this, using the name of your form, as a string argument:
var form = (Form)Activator.CreateInstance(Type.GetType("YourNameSpace.UserManagement"));
form.Show();
One straightforward, but not necessarily very clean solution would be to store the forms right there in the Tag property of your menu items, rather than the strings.
Somewhere at the beginning of your application, you'd have to assign these instances:
myUserManagementItem.Tag = new UserManagement();
myGroupsManagementItem.Tag = new GroupManagement();
Then, in the click event, you could shorten your code to:
ToolStripMenuItem aa = sender as ToolStripMenuItem;
Form form = aa.Tag as Form;
form.Show();
Cleaner solutions would include the following:
Provide separate event handlers for different menu items.
Derive your own menu item types that store the form to show in a strongly-typed property.

Accessing controls on a new form

I have 2 forms in my project, form1 and form2. When I click in a button in form1 I run this code:
Form tempform = new Form2();
tempform.Show();
In my code for Form2 I have a label which I now need to change the text.
How can I access the label?
I tried:
tempform.label1.value = "new text"
And that didn't work, I even tried to access using the Controls collection but I think I messed that up. Is there any way I can access the label? OR is there any way I can pass a value to that new form and then have that form alter the label text.
Thanks
If the label value should only be set once, when the form is created, then use a constructor for Form2 like this:
public Form2(string labelValue)
{
_labelValue = labelValue;
}
and then call that constructor when you create the form.
Alternatively, if the label changes over the lifetime of the form, make a public property:
public string LabelValue
{
get { return label1.Text; }
set { label1.Text = value; }
}
Also I would recommend naming the parameters and/or properties to reflect the meaning of the value, for example "titleText" instead of "labelValue". That way Form2 can decide how it wants to display the information (in the title bar, a label, a textbox, etc), and Form1 doesn't have to worry about that.
Edit: Consume the LabelValue property like this:
Form2 newForm = new Form2(); // Assign object to a Form2 instead of Form
newForm.LabelValue = "new text";
newForm.Show();
Controls have protected access by default. You can change that to public, or you can add a method/property to your form2 class to set the label and call that (latter method is generally preferred to preserve encapsulation and because the designer may want to overwrite your public change.).

Categories

Resources