Reputation: 1237
Well normally I am quite good at figuring and researching problems without guidance however I have come across a snag. I am trying to create an "Event" with C# (which I have not done before) everything I have looked up has nothing to do with what I need.
I am trying to call a class on my main form when form2 is hidden. I found some code which was supposed to check to see if form2 closed - Either I didn't integrate it into my code properly or closing is different to hiding.
So just to clarify I want to run through the program like this:
Upvotes: 8
Views: 11012
Reputation: 107
Also,
you can use VisibleChanged
event in Form2
private Form2_VisibleChanged(object sender, EventArgs e)
{
if (!this.Visible) { Refresh(); }
}
This might be more elegant...
Upvotes: 7
Reputation: 8386
If I understand correctly, you want to have a class that stores settings information that both Form1 and Form2 can access. Let's call that class Form1Settings
, and implement as:
public static class Form1Settings
{
public static string ButtonText;
public static string Uri;
}
For simplicity, I made this class and its properties static, so both Form1
and Form2
have direct access to it, removing the need for a refresh method.
Form1
would call Form2
in a blocking way, and only update its display if the OK button was clicked.
public partial class Form1 : Form
{
private Form2 form2 = new Form2();
public Form1()
{
InitializeComponent();
}
private void buttonSettings_Click(object sender, EventArgs e)
{
if (form2.ShowDialog() == DialogResult.OK)
{
this.button1.Text = Form1Settings.ButtonText;
this.textBoxUrl.Text = Form1Settings.Uri;
this.Update();
}
}
}
And finally, Form2 will update the settings values with input from the user:
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
private void buttonOK_Click(object sender, EventArgs e)
{
Form1Settings.ButtonText = this.textBoxButton.Text;
Form1Settings.Uri = this.textBoxUri.Text;
this.DialogResult = DialogResult.OK;
this.Hide();
}
}
Upvotes: 2
Reputation: 8201
Open the second form as modal
Form2 form2 = new Form2();
DialogResult result = form2.ShowDialog();
check the result and refresh:
if (result == DialogResult.OK)
Refresh();
What you also need to do in this case is when closing the form set DialogResult of the form, for example if you have an OK button, in the button handler set:
this.DialogResult = DialogResult.OK;
This will automatically close the form as well as I remember correctly.
What you can also do is set DialogResult.Cancel on cancel button if you need that.
Upvotes: 3
Reputation: 2416
Why not open Form2 as a modal dialog using ShowDialog()
? That way you may return a value if Form2 was closed by OK
or by Cancel
and act accordingly in Form1 after the call returned.
Upvotes: 1