Do something when form is closed - c#

how do I check if a form is closed?
I want to reload a listview's items when I close another form.
What I'm doing is:
Form1 = form with ListView
Form2 = form with TextBoxes
Opening a new form.
Creating a new folder via a textbox.
When I press "Add" in Form2 I want to reload the "ListView" on Form1.
So how am I supposed to do this?
And sorry for my bad English :(.

The simplest answer is to make a public method on Form1, let's call it RefreshList() and in your button click event on Form2, you simply call Form1.RefreshList. Here's a quick sample:
Form 2:
public Form1 ParentForm { get; set; }
private void Button_Click(object Sender, EventArgs args) {
{
// After the rest of your handler
if(ParentForm != null)
ParentForm.RefreshList();
Close(); // Close Form2 here, we're done!
}
Form 1:
private void ShowForm2()
{
Form2 form2 = new Form2();
form2.ParentForm = this;
form2.Show();
}
public void RefreshList()
{
// do your refresh here
}
Initially you mention that you want to do this when Form2 closes, but then later you mention that you want to do it "When I press "Add" in Form2 I want to reload the "ListView" on Form1." As others have mentioned, you can use the Closed event, so I took this approach to address your second case.

In Form1, you can subscribe to From2's FormClosed event.

You can handle the form Closing event as the Closed Event is obsolete if you are using anything above dot net 1.1

You can handle the FormClosed event if you simply want to react to when a particular form is closed. If you want to take it a step further, there is a FormClosing event that you could also handle and even prevent the form from closing if need to.

Having Form1 add an event handler to Form2's FormClosing event is an excellent option. However, there is an even simpler solution if Form2 is a dialog window. In other words, if it's OK for Form1 to be effectively locked and disabled while Form2 is displayed, you can simply show Form2 as a dialog window. Dialog windows show synchronously, so you can simply update the list immediately after showing Form2 and it won't hit that list-updating code until after Form2 is closed. For instance:
form2.ShowDialog(this);
updateList();

Related

Detect CloseEvent through different forms

PROBLEM SOLVED
SHORT STORY
I want to detect "FormClosing()" event through different forms, ie, when form1 is closed that is instantiated within form2, can form2 detect when user presses exit in form1?
LONG STORY
My team and I are working on a windows form application. Project has two forms: one is the main form page and the other is accessed via this main form. Main form looks like this:
And the second one looks like this:
If you press "Ekle/Sil" buttons within the main form, you are directed to form 2 where you can edit database entries. When you press "Sayfayı Yenile" button in the main form, the content of the text areas are refreshed by re-fetching entries from the database.
My problem is, I want to automatically refresh the main form when the user closes the second form. My research suggests I should use an "FormClosing()" event to detect a closing form. However, I want to detect this from the main form. Instantiating main form in second form's source code doesn't seem to be a reliable solution. Anyone can tell me how to do this?
EDIT
I solved the problem:
1) Created a public method within the main form that refreshes the page.
2) Send "this" property from the main form when creating the second form.
3) Added an "FormClosed()" handler within the second form that invokes this public method.
Still, I'm looking for a better solution.
EDIT 2
Better solution InBetween's answer
Simply use the Form.Closed event of the new child windows form. Everything is handled from the main form:
void EkleSil_Clicked(object sender, EventArgs e) //or whatever method is called when button is clicked
{
var newChildForm = new ChildForm();
newChildForm.Closed += childFormClosed;
newChildForm.Show();
}
void childFormClosed(object sender, EventArgs e)
{
((Form)sender).Closed -=childFormClosed;
updateShownData();
}
You can create a event in the second form and raise it when the form is closing .
Handle the event in the main form and refresh the main form when the event is raised
Another option would be to pass Form1 as an argument to Form2. Then use the Form.Closing event in Form2 and use the Form1 reference to trigger something.
Form1 form1Ref;
public Form2(Form1 mainform)
{
form1Ref = mainform;
}
private void Form2_FormClosing(object sender, FormClosingEventArgs e)
{
form1Ref.SomeMethod();
}

C# propery closing of an application when a form is still open

What's the proper way to close application with clicking on X in built in menu strip. Let's say that my Form1 opens Form2, when I close my Form2 my Form 1 stays open. What I want to achieve is that my application stops when I close my Form2. Does anybody know how to achieve this and how to reference it to X button on built in menu strip.
Try this:
Application.Exit();
In case it doesn't work, you have to provide more information and be more specific with code
In Form2 you could Register to the Closing Event in constructor something like this:
public Form2()
{
this.FormClosing += Form_OnClosing;
}
Then in the event close the Form1 and/or exit the application
private void Form_OnClosing(object sender, EventArgs args)
{
Application.OpenForms[0].Close();
Application.Exit();
Environment.Exit();
}
Try it
form2 F2 = new form2();
F2.ShowDialog()
I think you have a trouble with create new form children

Refresh an open form from another open form

I want to refresh an already opened form (form1) from another opened form's (form2) button_click(). In form1 I display the data saved by form2 and when form1 is already opened I want it to refresh if new data is saved on form2 in order to display it.
The problem is that I've tried iterating through `Application.Openforms`, but it turns out that it is read-only and I cannot access the form once found and I don't know how to access *form1* from *form2*, since I can't simply find it.
How can I access *form1* from *form2*?
Edit:
Form1 is actually opened from Form2.
The problem with Application.Openforms is that , as I've stated, a read-only list of forms already opened and I cant actually access the forms through it. They simply don't have the methods for it, I sugest you try using Application.OpenForms and look it up if you don't know how it works.
Also it's pointless to show what I've already tried because it includes Application.OpenForms, but for the sake of information:
FormCollection of = Application.OpenForms;
foreach (var f in of)
{
if (f.GetType().ToString() == "Kontrl_Doc.Visualizar")
{
f.Refresh();
}
}
When I click the button (button_click()) in Form2 it checks if Form1 is open or not. If Form1 isn't open it opens one and if it is than I'd like it to refresh it. Simultaneously, it closes Form2 and opens Form2 again, in order to reset is fields.
What I wan to do is, if the form1 is already opened , it form2 should tell it to refresh the already opened window with the form 1.
"Form1 is actually opened from Form2" - If this is the case, then just call Refresh using the form variable that you have in Form2. If necessary, make that a private field in the Form2 class or store it in an array for later use.
For example:
(Somewhere in Form2)
Form1 form1 = new Form1();
form1.Show();
(Inside the button click in Form2)
form1.Refresh();
you can use events. In form2 you place this code
public event Action ReloadForm1;
//on the place where you will reload form1
ReloadForm1();
and in form1 if you have opening form2:
form2.ReloadForm1 += Reload;
//outside method
void Reload()
{
this.Reload();
}
Create a void method in form1 and add the components u want to refresh maybe you want to reload a dropdown from db
public void Refresh()
{
...
}
then open a dialog of form2
catch the dialog result

Owned form and mdi parent

this is my scenario and hope you can solve it for me
I have a MDI container form called "MainForm". In MainForm there is a simple form call "Form1". In Form1 there is a button. every time you pushed it, It open a new form which instance of "Form2". The followng code is click button event.
Button_Click()
{
Form2 frm=new Form2();
frm.mdiparnt=this.MdiParent;
this.addOwnedForm(frm);
frm.Visible=true;
}
and the following code tries to close owned forms when the user close Form1
Form1_CloseEvent()
{
foreach(var item in this.ownedForm)
{
item.close();
}
}
But when the debugger steps into close event, just close Form1, and the form2 instances remain open. what should I do to solve it
I think you are not setting up the event. Do it like this.
Add it to your Button_Click() method:
this.FormClosed += Form1_FormClosed;
Here is the method:
void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
foreach(var item in this.ownedForm)
{
item.close();
}
}
first of all this code does not compile!
you have several syntax errors: mdiparnt, addOwnedForm, ownedForm, close
you are probably not sharing your actual code and that's gonna be a problem to help you if it's not your code.
now in Button_Click() event you are doing
frm.mdiparnt=this.MdiParent;
this.AddOwnedForm(frm);
even though you only need
this.AddOwnedForm(frm);
or an exception will be thrown. i've checked this code and it's working just fine

DialogResult that doesn't close the form?

I have a form Form1 from which I display Form2 as a modal form. From Form2 I do all sort of editing and deleting of different set of values which should be reflected in Form1 after closing Form2. So what I do is RePopulateControls_in_Form1() after closing Form2. Since RePopulateControls_in_Form1()is a long process, I want to execute that method only if some modification (edit,add, delete) happens in Form2 and not when Form2 is just opened and closed.
So this is what I try to do in Form1:
Form2 f = new Form2();
if (f.ShowDialog(this) == DialogResult.Something)
RePopulateControls_in_Form1()
And then in Form2 I do,
private void bntEdit()
{
//If Edit?
this.DialogResult = DialogResult.Something;
}
private void bntAdd()
{
//If Add?
this.DialogResult = DialogResult.Something;
}
private void bntDelete()
{
//If Delete?
this.DialogResult = DialogResult.Something;
}
But my problem is .Something. If it is anything other than .None, Form2 simply gets closed. I do not want Form2 to get simply closed by its own unless the user closes it.
If I do this:
//in Form1
private void Form1_Click()
{
Form2 f = new Form2();
if (f.ShowDialog(this) == DialogResult.None)
RePopulateControls_in_Form1()
}
//in Form2
private void Form2_SomeModification()
{
//If Modified?
this.DialogResult = DialogResult.None;
}
RePopulateControls_in_Form1() is not hit!
In short, in my program how can I tell the compiler to call RePopulateControls_in_Form1() only if values are modified in Form2?
Note: Repopulating is certainly required since the controls are dynamically created and a bit complex (actually what is created in Form2 is GUI controls and its labels etc).
Setting DialogResult on Form hides the form and returns from ShowDialog. If you want to delay that until the user performs some other action (such as closing the form) you should store that state as a member field and set DialogResult in a handler for Form.Closing.
Also, if you do want to dismiss the modal form on a button press, you can use the Button.DialogResult property instead of making a Button.Click handler.
A simple way might be not to use DialogResult at all but a dedicated property not interfering with the Form's behavior. - Then you should be able to program any logic you want.
I would use an event in Form 2. Fire that event when your Form2 is closing. Handling that event in Form1 would allow you to carry out any processing you want to. Further if needs be you could pass back some information from Form2 to Form1 in parameters to the event.
An alternative would be to set up a Global static variable - maybe just a bool. Then Form2 can set it to true or false depending on whether there are changes made. Form1 can read this when Form2 returns and if true carry out processing and set it back to false.

Categories

Resources