Unable to Open ChildForm inside MdiParent - c#

I am trying to open ChildForms on MdiParent Form using a Form Manager Class.
I've tried several alternatives in order to tell "FormManager" Class which Form is the MdiParent; however it would always throw errors (1 different error for each different occasion).
Most of the times it would say that MainForm was not a MdiContainer; and this is not true as I had set MainForm previously as such.
Note:1 Main Form is set as a MdiContainer.
Note:2 If I attempt to open only 1 Form it will open perfectly inside MdiParent Form. However if I attempt to Load 2 or more Forms it will throw error.
Note:3 If I create the Child Forms Instances on Main Form; Everything works just fine. No issues at all. But this is not how I want to do it.
// [Class] : Main Form
// Member Variables
private FormManager FrmMgr;
// Load Forms using FormManager Class
private void Load_Forms()
{
// Create a new Instance of FormManager.
if (FrmMgr == null) { FrmMgr = new FormManager(); }
// Set MainForm as MdiParent in FormManager Class
FrmMgr.MdiParent = this;
// Alternatively Manually Set the MdiParent in MainForm (Uncomment Line Bellow)
// this.IsMdiContainer = true;
}
// [Class] : Form Manager
// <Member Variables>
private Form1 frm1;
private Form2 frm2;
// FormManager <Constructor>.
// Constructor Receives MdiParent Information from MainForm
// and Sets the MdiParent.ActiveControl Information to Every Form
// when calling each (Form initiation) Method.
public FormManager(Form _MainParent)
{
// Create new Instance of Form1
Init_Frm1(_MainParent);
// Create new Instance of Form2
Init_Frm2(_MainParent);
}
private void Init_frm1(_MainParent)
{
if (frm1 == null) { frm1 = new Form1(); }
frm1.MdiParent = _MainParent;
frm1.Show();
}
private void Init_frm2(_MainParent)
{
if (frm2 == null) { frm2 = new Form2(); }
frm2.MdiParent = _MainParent;
frm2.Show();
}
}
Can anyone point me in the right direction and help me understand why this happens?
Thanks in advance.

I was finally able to sort it out.
The issue seemed to be consisted in the way I've used to pass "MainForm" as the "MdiParent" to "FormManager" class.
// [Class] MainForm
// Create new Instance (Always Active); of FormManager Class
// Note: When FormManager Class is Loaded; it's Constructor will
// run the Methods that will open all the initial Forms.
private void Load_Modules()
{
// "this" refers to "MainForm"
if (FrmMgr == null) { FrmMgr = new FormManager(this); }
}
// [Class] FormManager
// Member Variables
private Form1 frm1;
private Form2 frm2;
// <Constructor>
public FormManager(Form _MainParent)
{
// Create new Instance of Form1 under "Init_Frm1" Method
Init_Frm1(_MainParent);
// Create new Instance of Form2 under "Init_Frm2" Method
Init_Frm2(_MainParent);
}
// Method that Will Create new Instance of Form1
private void Init_Frm1(Form _MainParent)
{
if (frm1 == null) { frm1 = new Form1(); }
frm1.MdiParent = _MainParent;
frm1.Show();
}
// Method that Will Create new Instance of Form2
private void Init_Frm2(Form _MainParent)
{
if (frm2 == null) { frm2 = new Form2(); }
frm2.MdiParent = _MainParent;
frm2.Show();
}

Related

how to prevent my program to open the same window Form twice

i am working on a project, i am creating a instance and opening a specific form in my program, like i use following code to open a form:
frm2 cs = new frm2();
cs.Show();
but the problem here is each time i click on the button it just open a new windows and the previous one is also opened, all i want to do here is when i click on button and that window is already open then it simply go to already opened windows except opening the new one.
hope you guys understand my question and will help me doing it.
EDIT:
i tried this code : the code i wrote in frm2.cs file is:
public partial class frm2 : Form
{
private static frm2 _form2 = null;
public frm2()
{
InitializeComponent();
}
public static frm2 Instance
{
get
{
if (_form2 == null)
{
_form2 = new frm2();
}
return _form2;
}
}
and in frmMain.cs file where i code to access the instance and open the project is :
private void addProductToolStripMenuItem_Click(object sender, EventArgs e)
{
frm2.Instance.Show();
//frm2 cs = new frm2();
//cs.Show();
}
it work fine the first time, but when i open the frm2 , close it and then again try to open it the compiler give error at frm2.Instance.Show(); and the error comes is
: Cannot access a disposed object.
Object name: 'frm2'.
Save the instance of the form opened in a global class variable and then, if this variable is not null just call Show instead of opening againg. Some tips should be followed though
public class Form1: Form
{
private frm2 _currentInstance = null;
....
if(_currentInstance == null)
{
_currentInstance = new frm2();
_currentInstance.FormClosed += instanceHasBeenClosed;
_currentInstance.Show();
}
_currentInstance.BringToFront();
....
private void instanceHasBeenClosed(object sender, FormClosedEventArgs e)
{
_currentInstance = null;
}
}
It is important to subscribe to the FormClosed event for the _currentInstance. In this way your Form1 will be notified when your user closes the instance. And you could reset the internal variable to null, so at the subsequent click you could reopen again the instance
There is also the possibility to use the Application.OpenForms collection to check if your form is shown
frm2 f = Application.OpenForms["NameOfForm2"];
if(f != null)
f.BringToFront();
else
{
frm2 f = new frm2();
f.Show();
}
I know you don't want to write that much code but it seems this is the only way to go.
At least, you can separate that code from your forms by writing a generic code.
var f = FormManager.Show<Form2>(); //create a new form.
f = FormManager.Show<Form2>(); //show the existing form.
f.Close();
f = FormManager.Show<Form2>(); //create a new form
public static class FormManager
{
static Dictionary<Type, Form> _Forms = new Dictionary<Type, Form>();
public static T Show<T>() where T: Form, new()
{
var type = typeof(T);
Form f = null;
if(_Forms.TryGetValue(type,out f))
{
f.BringToFront();
}
else
{
f = new T();
f.FormClosing += (s, e) => _Forms.Remove(s.GetType());
_Forms.Add(type, f);
f.Show();
}
return (T)f;
}
}
you can use singleton design pattern to return always the same instance
public partial class Form2 : Form
{
private static Form2 _form2 = null;
private Form2()
{
InitializeComponent();
}
public static Form2 Instance
{
get
{
if (_form2 == null)
{
_form2 = new Form2();
}
return _form2;
}
}
}
// use this to call the instance
Form2.Instance.Show();
Singleton pattern may be a way to go - just apply it to windows forms (you can check this link for the description of the singleton pattern in C#: http://msdn.microsoft.com/en-us/library/ff650316.aspx).
Check on multiple buttons in that Form is open or not:
private bool isOpen(string name)
{
IsOpen = false;
foreach (Form f in Application.OpenForms)
{
if (f.Text == name)
{
IsOpen = true;
f.Focus();
break;
}
}
if (IsOpen == false)
{
return IsOpen;
}
return IsOpen;
}
Call this in the button click to Check the current Form:
if (isOpen("Item Import Master")) ;
else
{
Item_Import_Master obj1 = new Item_Import_Master();
obj1.Show();
}
You need to check if a form is Disposed before you show it again, otherwise you get Cannot access a disposed object exeption
something like this should work
private static AdvancedRDSWindow form2;
private AdvancedRDSWindow()
{
InitializeComponent();
}
public static AdvancedRDSWindow Instance
{
get
{
if (form2 == null || form2.IsDisposed)
{
form2 = new AdvancedRDSWindow();
}
return form2;
and then you can show it with a button for instance
private void AdvancedRDS_Click(object sender, EventArgs e)
{
AdvancedRDSWindow.Instance.Show();
}
Use this code in the button click event
If the form is already opened, it will bring the form to front
# Here is my code.. #
foreach (Form form in Application.OpenForms)
{
if (form.GetType() == typeof(frm2))
{
form.Activate();
return;
}
}
frm2 frm = new frm2();
frm.Show();

How will my form 1 know that the checkbox is enabled from form 2?

This is my form 2, this is where the checkboxes are.
My operator in here which is on the middle, has a random character generator, which my code is this :
char[] select = new char[] { '+', '-', '/', '%', '*' };
var rand = new Random();
char num = select[rand.Next(5)];
lbloperator.Text = Convert.ToString(num);
If the only check is addition, my form 1 will only perform addition, or if add,subtract, my form 1 will only perform add and subtract. Please help me with this! :(
FORM1
There is tow ways to do that:
1- first way is define public property in form2 that can tell form1 the status of checkBox1:
Form2:
public bool MyCheckBoxStatus
{
get {return checkBox1.Checked;}
}
Form 1 (For Example):
Form2 frm = new Form2;
frm.ShowDialog();
if (frm.MyCheckBoxStatus)
{
//Do something...
}
2- The other way: if you are using Windows Forms Application then all your controls have a property named Modifiers change its value to public and write this code in Form1:
Form2 frm = new Form2;
frm.ShowDialog();
if (frm.checkBox1.Checked)
{
//Do something...
}
Try this:
public partial class Form2: Form
{
public string checkBoxSelected = "";
}
public partial class Form1 : Form
{
private void MakeResult()
{
Form2 result = new Form2();
result.checkBoxSelected = "+";
result.Show();
}
}
I'm not too sure exactly what you are asking, but it sounds like you are trying to pass some data between forms.
In Form2, you can add a public property that reads your label
public string TheOperator {
get { return lblOperator.Text; }
}
Then from Form1, you can create a new instance of form2 and then reference the Property when needed.
Form2 fm = new Form2();
fm.Show();
string theOp = fm.TheOperator;
//////////
In response to your edit:
You can add this to Form1, exposing the operator variable there:
public string MyOperator {
get { return lblOperator.Text; }
set {
lblOperator.text = value;
//You can perform any updates to
//your calculations here, or call
//another method to do so
}
}
private void OpenForm2()
{
Form2 frm2 = new Form2(this);
frm2.Show();
}
Then inside of Form2, you pass a reference to Form1 so that you can access the public property:
private Form1 frm;
public New(Form1 _frm)
{
frm = _frm;
}
private void UpdateOperator()
{
//call this method, calculating your operator and then
//set the operator on the first form (variable frm) to
//What you need it to do
frm.MyOperator = lblOperator.Text;
}

Create global method to show Forms

Form1 frm = new Form1();
frm.mdiParent=this;
frm.show();
I want to create a global method showFrm(Form formToShow) which i can access from anywhere in my project.
I've tried.
public void showFrm(Form formToShow)
{
formToShow f=new formToShow();//getting error here
f.mdiParent= mdiForm;
f.show();
}
Put this method in your "only parent form" class:
public void ShowMdiChild<T>() where T: Form, new()
{
var form = new T();
form.MdiParent = this;
form.Show();
}
Usage:
yourOnlyParentForm.ShowMdiChild<SomeForm>();
I would also remind you that C# is case-sensitive.

How to check if the Form object is till running with C#

Let's say, I have 2 WinForms here, Form1 and Form2 respectively. And then I made Form1 hidden. I wonder how I could write the code in Form2 to detect if Form1 object is still running or not.
I was trying to use Form1.ActiveForm but it seems to give me NULL value. Any better ideas? Thanks.
You could use my method to get any active forms:
public static Form IsFormAlreadyOpen(Type FormType)
{
foreach (Form OpenForm in Application.OpenForms)
{
if (OpenForm.GetType() == FormType)
return OpenForm;
}
return null;
}
If you mean by running "is still in memory" then you could
simply test the reference to the form: if(form1 != null)
after that you could test for being hidden: if(form1.Visible)
and possibly minimized: if(form1.WindowState != FormWindowState.Minimized)
If you want to check whether your form has been closed (and therefore disposed) you can try calling a method from that form and catching the ObjectDisposedException.
try
{
Form1.SomeMethod();
}
catch (ObjectDisposedException ex)
{
// Form has been closed
}
If the form hasn't been closed, and you want to check whether it's visible or not, you can use it's "Visible" property
It looks to me that you are trying to access Form1 as a static instance and unless you have created Form1 in this manner you will not be able to access it and this could be why you are getting NULL values from your function. If you want to reference Form1 from Form2 then you need to pass it a reference.
Form1:
public class Form1
{
public Form1()
{
}
}
Form2:
public class Form2
{
private Form1 _frm1;
public Form2(Form1 frm1)
{
_frm1 = frm1;
}
}
Now when you create your instance of Form2 you declare it like...
Form2 frm2 = new Form2(frm1);
Where frm1 is the instance of Form1.
Now whenever you need to refer to Form1 from Form2 you can refer to it via _frm1.
private Form GetForm()
{
Form mdiParent = this.MdiParent;
Form1 objForm
foreach (Form frm in mdiParent.MdiChildren)
{
objForm = frm as Form1;
if (objForm != null)
{
objForm.Activate();
return objForm;
}
}
return null;
}

stackoverflow exception in form class

When I try to create an object of the form class within the form class, it gives an exception as stackoverflow occured.However, when I declare the object of form class within a method,it works fine.the code is as follows:
namespace WindowsFormsApplication6
{
public partial class Form1 : Form
{
**Form1 f1 = new Form1();**//gives stackoverflow exception.......
char[] ar = new char[15];
int flag = 0, end;
double val1, val2, res;
string oprt;
public Form1()
{
InitializeComponent();
}
private void masters(object sender, EventArgs e)
{
ar[i] = char.Parse(((Button)sender).Text);
if (char.IsDigit(ar[i]))
{
if (flag != 0)
{
if (textBox1.Text == oprt)
{
textBox1.Clear();
}
}
else
{
if (end == 1)
{
textBox1.Clear();
end = 0;
}
}
Button ansbox = sender as Button;
textBox1.Text += ansbox.Text;
}
else if (char.IsSymbol(ar[i]))
{
if (textBox1.TextLength != 0)
{
val1 = double.Parse(textBox1.Text);
textBox1.Clear();
Button bt = sender as Button;
if (bt != null)
textBox1.Text = bt.Text;
oprt = bt.Text;
// dot.Enabled = true;
flag = 1;
}
}
}
private void button14_Click(object sender, EventArgs e)
{
if (textBox1.TextLength != 0)
{
val2 = double.Parse(textBox1.Text);
switch (oprt)
{
case "+": res = val1 + val2;
break;
case "-": res = val1 - val2;
break;
case "*": res = val1 * val2;
break;
case "/": res = val1 / val2;
break;
}
textBox1.Text = res.ToString();
flag = 0;
end = 1;
}
}
}
}
}
Creating an instance of Form1 would cause the f1 property to be initialised with an instance of Form1 which would cause the f1 property to be initialised with an instance of Form1 which would cause the f1 property to be initialised with an instance of Form1 which would cause the f1 property to be initialised with an instance of Form1 which would cause the f1 property to be initialised with an instance of Form1 which would cause the f1 property to be initialised with an instance of Form1 which would cause the f1 property to be initialised with an instance of Form1 which would cause the f1 property to be initialised with an instance of Form1 which would cause the f1 property to be initialised with an instance of Form1 which would cause the f1 property to be initialised with an instance of Form1 which would cause the f1 property to be initialised with an instance of Form1 which would cause the f1 property to be initialised with an instance of Form1 which would cause the f1 property to be initialised with an instance of Form1 which would ... Stack Overflow!
Within a method in the class, the 'f1' would be local and only exist for the life of the call. Unless you called the same method on the instantiated Form1 then there wouldn't be subsequent Form1s created.
You're creating an private instance of Form1 when Form1 is created so this is sort of an endless loop:
Somewhere in your code you create your first Form1 instance.
When this instance is creating it creates a new instance of Form1.
This instance also creates an instance of Form1 and again, and again etc.
So when an instance is created all variables are initialized and when you declare them like this:
Form1 f1 = new Form1() this automaticly instatiates a new instance of the form.
I suggest you don't have a new instance of your Form1 inside your Form1 but if you really need this create a method to make the instance:
Change the Form1 f1 = new Form1(); into Form1 f1;.
And create a method:
public void InstantiateNewForm1Instance()
{
f1 = new Form1();
}
But: DON'T CALL THIS METHOD IN THE CONSTRUCTOR! Or else you will have the same problem :-)
That's because every time you create an instance of your class, it creates another instance of your class and so on...and so on...and so on...
In other words, you have a infinite recursion when you try to create an instance of your class.
You need to add some kind of control around whether or not a new instance of Form1 gets created at construction time. A simple (and not complete) solution would be something like:
public partial class Form1 : Form
{
Form1 f1;
public Form1() : this(false)
public Form1(bool createNewInstance)
{
if(createNewInstance)
f1 = new Form1();
else
f1 = null;
}
}
The form is instantiated, then it processes the private fields, which instantiates the form1, which then instantiates the private fields (finding form1), which then instantiates that object and processes the private fields, continuing on.
So that is why that happens, whereas, in a method, a method only executes when called, no internal initialization.
Why, when in form1, do you need another instance of the same form?
Could it be because Form1 is trying to instantiate another Form1 which in turn is trying to instantiate another Form1 etc?
If you're in the new constructor of Form1, an instance of Form1 is already being created. So, before it's finished being created, you're creating another, then that one does the same. Before your program loads, too many form1s are going on the stack...overflowing the stack.
If each Form1 class contains one new instance of a Form1 class, you are bound to have a stack overflow exception when trying to create one.
You can see it more clearly by trying to draw the objects on a sheet of paper, simulating the space they occupy in memory and the space occupied by their children - but remember, each Form 1 must be of the same size!

Categories