Relationship between the two forms - c#

Methods opening forms :
form1 --> form2 --> form3
ChecklistBox on the form1 there. How to know the form3 That is active or not?

If the forms you are referencing are MDI child forms, you could use
Form activeChild = this.ActiveMdiChild;
else you could use the following code if not using MDI child forms.
Form currentForm = Form.ActiveForm;

I understand that you are asking if form 3 is opened. If that is incorrect, please enlighten me.
There are probably dozens of ways to do so, it all depends on what you want to do.
One simple way would be to leave a flag somewhere, say in your Program.cs file:
public static bool Form3IsOpen = false;
Then:
private void Form3_Load(sender object, EventArgs e)
{
Program.Form3IsOpen = true;
}
And:
private void Form3_Close(sender object, EventArgs e)
{
Program.Form3IsOpen = false;
}
Supplemental:
You can also keep a reference to your subform:
In form1.cs:
private Form2 FormChild;
//In the function that opens the Form2:
FormChild = new Form2();
FormChild.Show();
Form2 will have something similar to retain Form3. If one form can open several, just use an array or collection.

When i usually have many different forms and only one instance to be created, i put them in dictonary and check it if there is a form.
Something like this:
public static Dictonary<string, Form> act_forms_in_app = new Dictonary<string, Form>();
now in every forms creation i do it like this
Form1 frm = new Form1();
frm.Name = "Myformname"
//set its properties etc.
frm.Load => (s,ev) { act_forms_in_app.Add(frm.Name, frm);};
frm.Load += new EventHandler(frm_Load);
frm.Disposed => (s, ev) { act_forms_in_app.Remove(frm.Name)};
//your usual form load event handler
public void frm_Load(object sender, EventArguments e)
{
...
}
somewhere where you want to check
Form frm = //Your form object
if(act_forms_in_app.ContainsKey(frm.Name))
{
//Perform as required
}

Related

Freeing or clearing created objects

I have 2 windows forms; Form1.cs and Form2.cs.
Here are the code for Form1.cs in which will show the Form2.cs and Hide the the current Form1.cs
private void button1_Click(object sender, EventArgs e)
{
Form2 f2 = new Form2();
f2.Show();
this.Hide();
}
Here are the code for Form2.cs in which will show the Form1.cs and Hide the the current Form2.cs
private void button1_Click(object sender, EventArgs e)
{
Form2 f2 = new Form2();
f2.Show();
this.Hide();
}
I have monitored the memory usage of the application and I have noticed that the memory usage of the application is increasing every time I execute the code above.
You're creating new forms on each button click, so you hold many instances in memory after clicking the buttons multiple times.
You're probably looking for this.Close() instead of this.Hide(), as the former will close and dispose the current form while the latter will only hide it.
If you want to hide and re-show the forms, you need to keep a reference to the forms. There are a lot of considerations (should a form be instantiated only once, or each time it is requested? Should it be possible for multiple instances of the same form be opened? And so on) and possible patterns and (third-party) solutions (e.g. Application Controller, What is a proper way of building Winform apps with multiple “screens”).
One solution would be to simply create your own form registry where each form has a singleton:
public static class FormRegistry
{
private static Lazy<Form1> _form1 = new Lazy<Form1>(() => new Form1());
public static Form1 Form1
{
get
{
return _form1.Value;
}
}
private static Lazy<Form2> _form2 = new Lazy<Form2>(() => new Form2());
public static Form2 Form2
{
get
{
return _form2.Value;
}
}
}
Then anywhere in code, you can just do FormRegistry.Form1.Show(). Please note this code is a proof of concept with many issues and much room for improvement, but it's there to give you the general idea.

Switching between forms and sending variable correctly

I am wondering how can I correctly switch between forms by button click event.
I have Form1 and Form2.
Form1 have: -TextBoxForm1
-ButtonForm1
Form2 have: -TextBoxForm2
-ButtonForm2
I would like to on_click ButtonForm1 event go to the Form2. Then I want to write some message to TextBoxForm2 and press ButtonForm2 it will go to the Form1 again and message from TextBoxForm2 will appear in TextBoxForm1.
Everything works fine, but I have one problem. When I close application and I wanna debug and start it again, some errors appear like:"application is already running".
Form1:
public static string MSG;
public Form1()
{
InitializeComponent();
TextBoxForm1.Text = MSG;
}
private void ButtonForm1_Click(object sender, EventArgs e)
{
Form2 form2 = new Form2();
this.Hide();
//There is probably my fault but when I was trying this.Close(); everything shutted down
form2.Show();
}
Form2:
private void ButtonForm2_Click(object sender, EventArgs e)
{
Form1.MSG = TextBoxForm2.Text;
Form1 form= new Form1();
form.Show();
this.Close();
}
How can I do this correctly please? :) I am beginner, thank you!
I would not go the route of using a STATIC for passing between forms as you mention you are a beginner, but lets get the closing to work for you.
In your main form create a new method to handle an event call as Hans mentioned in the comment. Then, once you create your second form, attach to its closing event to force form 1 to just become visible again.
// Inside your Form1's class..
void ReShowThisForm( object sender, CancelEventArgs e)
{
// since this will be done AFTER the 2nd form's click event, we can pull it
// into your form1's still active textbox control without recreating the form
TextBoxForm1.Text = MSG;
this.Show();
}
and where you are creating form2
private void ButtonForm1_Click(object sender, EventArgs e)
{
Form2 form2 = new Form2();
form2.Closing += ReShowThisForm;
this.Hide();
form2.Show();
}
and in your second form click, you should only need to set the static field and close the form
private void ButtonForm2_Click(object sender, EventArgs e)
{
Form1.MSG = TextBoxForm2.Text;
this.Close();
}
Easy solution is to use modal form. Display Form2 temporarily, when it is displayed Form1 is invisible.
var form2 = new Form2();
this.Visible = false; // or Hide();
form2.ShowDialog(this);
this.Visible = true;
And to pass data you can define property in Form2, to example:
public string SomeData {get; set;}
Form1 has to set SomeData, which you take in Shown and display. Same property can be used to get data from Form2 (before closing).
// form 1 click
var form2 = new Form2() { SomeData = TextBoxForm1.Text; }
this.Visible = false;
form2.ShowDialog(this);
this.Visible = true;
TextBoxForm1.Text = form2.SomeData;
// form 2 shown
TextBoxForm2.Text = SomeData;
// form 2 click
SomeData = TextBoxForm2.Text;
Close();

How to close one FORM from another FORM in C# Winform Application

I'm working on C# winform application, in that I want to close one form from the another form i.e. I have 2 forms Form1 and Form2 and I want to close Form2 from Form1 for that I have written following code on button click event of Form1, but I'm getting the following exception-
"Object reference not set to an instance of an object."
private void button_click(object sender, eventArgs e)
{
Form2.ActiveForm.Disposed+= new EventHandler(closeForm2) // Getting Exception to ***closeForm2***
}
private void closeForm2(object sender, eventArgs e)
{
Form2.ActiveForm.Dispose();
}
For future readers!
You can use the following code to close one FORM from another FORM in C# Winform Application.
FrmToBeClosed obj = (FrmToBeClosed)Application.OpenForms["FrmToBeClosed"];
obj.Close();
Those 2 lines of code are self-explanatory!
That's it!
ActiveForm returns "Currently active form from this application" = Form you clicked...
How you start your Form2?
I think you should define it like
Form2 DetailsForm = null;
public void prepareForm2() //bind this to action to open new form
{
if (DetailsForm == null)
{
DetailsForm = new Form2(this);
}
}
Than you can just call close()/Dispose/Hide
by calling
private void closeForm2(object sender, eventArgs e)
{
DetailsForm.Close();
// or DetailsForm.Hide();
// or DetailsForm.Dispose();
}
See MSDN -> Form.ActiveForm Property
If your application is a multiple-document interface (MDI) application, use the ActiveMdiChild property to obtain the currently active MDI child form.
I think you need a void in your MDI-Form like
public void closeChild(Type FormType)
{
foreach(Form form in this.MdiChildren)
{
if(typeof(form) == FormType)
{
/* what ever you wanna do */
}
}
}
Hope I could help :)
CloseProgramForm closepf = new CloseProgramForm();
closepf.ShowDialog();
if (closeoption == 1)
e.Cancel = false;
else
e.Cancel = true;

If Else Condition For .Close?

i got 2 forms 1mdiparent, 1child
lets say mdiparent = Form1 then child = Form2 .
i got New button in Form1 calling childform (Form2) like:
private void newDocument_ItemClick(object sender, ClickEventArgs e)
{
Form2 formChild = new Form2();
Form2.Show()
}
now my question was whats the if else condition for : if Form2 == Close?
something like:
if (Form2.Close == true){ //condition }
or if (Form2 == Close){ //condition }
but i know its not the right code .so hope you could help me :) thanks .
If I understand your question correctly, you want to be notified by the system when the Form2 is closed so you could apply some internal logic to avoid the reopening of the child form and apply some kind of changes to your main interface.
If this is your problem then you could add your event handler for the FormClosing event of the Form2 directly in the code of Form1 when you open the Form2
// Flag to keep the state open/close of the child form
private bool childClosed = true;
private void newDocument_ItemClick(object sender, ClickEventArgs e)
{
if(childClosed == true)
{
Form2 formChild = new Form2();
// Setup the event handler form the Form2 closing directly here in the MDI
formChild.FormClosing += new FormClosingEventHandler(myFormClosing);
formChild.Show();
// set the flag to avoid the reopening
childClosed = false;
}
}
// Now, when the formChild closes, you will receive the event directly here in the MDI
private void myFormClosing(object sender, FormClosingEventArgs e)
{
// The child form is closing......
// Do your update here, but first check the close reason
if(e.CloseReason == CloseReason.UserClosing)
{
......
// reset the flag so you could reopen the child if needed
childClosed = true;
}
}
You will probably want to use either the Form.FormClosed event or the Form.FormClosing event. Probably the former since you don't really want to interact with the closing of the form.
You would create a method and have it called when the event is fired and this would do whatever you wanted (such as hide buttons and such like).
See http://msdn.microsoft.com/en-us/library/system.windows.forms.form.formclosed.aspx for details of the formclosed event.
When a form is closed, it's disposed too. Thus just check if it's disposed by following code:
Form2 formChild = new Form2();
// ...
if (formChild.IsDisposed) {
// Do someting
}
As #V4Vendetta pointed out: there is a FormClosing event (called before the form has closed. Used to tell the user "You haven't saved yet") and a FormClosed event (called after the form closed).
public class Form2 : Form
{
public bool hasClosed;
private void Form2_FormClosed(object sender, FormClosedEventArgs e)
{
hasClosed = true;
}
}
with this, you can do
if (formChild.hasClosed)
// do something
It is wrong to take this approach, the Form 2 is initialized in the button click event, therefore, you assume that the form object was not available.
if you want to change this order, then the form should be initialized somewhere else like the constructor of the Form 1.
private Form2 form2;
public Form1()
{
form2 = new Form2();
}
private void newDocument_ItemClick(object sender, ClickEventArgs e)
{
if(!form2.Visible)
{
form2.Show();
}else
{
form2.Hide();
}
}
Hiding a form is not same as closing a form, if you really open and close the form2 and carry out some action based on that, then you should set a property on the parent form when the form2 closing event is triggered, to do this you must pass the parent form as an argument in the form2 constructor.
You can check that with the help of the following code
foreach (Form f in Application.OpenForms)
{
if (f.Text == formName)
{
IsOpen = true;
break;
}
}
if(!IsOpen)
{....do your code....}

how would I show the original Form2 from inside Form1 when I press button on Form1 in C#

private void button1_Click(object sender, EventArgs e)
{
Form2.Show();
}
I have the code above which in my opinion contains no error but it won't execute by some reason.
It says the error "An object reference is required for the non-static field, method, or property" but what I have missed?
I have just two forms (Form1 and Form2) and one button nothing more. I used a registry cleaner but the error persists.
There exists another code for it which worked, but this code makes a copy of my form as a new variable, but I would like to show the original form like it Visual Basic did.
In addition to storing a reference to your Form at Class level, you need to check if it has been closed since the last time it was used. In that case you'd need to create a new instance (just as you do for the very first use). The below example also restores the form if it was minimized:
public partial class Form1 : Form
{
Form2 F2 = null;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
if (F2 == null || F2.IsDisposed)
{
F2 = new Form2();
F2.Show();
}
else
{
if (F2.WindowState == FormWindowState.Minimized)
{
F2.WindowState = FormWindowState.Normal;
}
F2.Activate();
}
}
}
Form2 or Form1 are just a names of classes. Before using of this classes you need to create an instance of them
Form2 secondaryForm = new Form2();
After this you can use all methods and properties of that class secondaryForm.Show();
So before using/showing your Form2, you need to create an instance. If you want show
your original form
, meens that instance are already created. You need check your code where that instance was created and put reference to that form in variable:
Create a variable in Form1:
private Form2 secondaryForm;
In code where you created already your original Form2 just use this variable:
this.secondaryForm = new Form2();
After this anywhere in Form1's code you can show a Form2 with next line:
this.secondaryFomr.Show();

Categories