I have a bunch of windows forms. Each form has "Back" and "Next" buttons for switching forms. For example, clicking "Back" on Form3 then we go to Form2. Then clicking "Next" button on Form2 then Form3 is shown.
Now my question is that if we click "Next" from the very beginning, it works smoothly. However if I click "Back" on Form3 then Form2 is displayed, then click "Next" on Form3 go to Form3. The code doesn't goto Form3_Load event.
What is wrong in my code?
public partial class Form3 : Form
{
Form2 FormPrev;
Form4 FormNext;
List<DataRow> drlist = new List<DataRow>();
DataTable dt = new DataTable();
public Form3(Form2 _FormPrev)
{
InitializeComponent();
this.FormPrev = _FormPrev;
}
private void btnCancel_Click(object sender, EventArgs e)
{
this.Close();
}
private void btnNext_Click(object sender, EventArgs e)
{
ShowNext();
}
private void btnBack_Click(object sender, EventArgs e)
{
ShowPrev();
}
private void ShowNext()
{
if (FormNext == null)
FormNext = new Form4(this);
FormNext.Show();
this.Hide();
}
private void ShowPrev()
{
FormPrev.Show();
this.Hide();
}
private void Form3_Load(object sender, EventArgs e)
{
// blah blah.
}
Thanks.
A form's Load event is only fired when the form is invoked for the first time. If you subsequently hide the form and reshow it then this is not reloading the form so the form's Load event is not fired.
If you want to use an event to handle when the form is re-displayed then you should look at the following more suitable events:
Activated
Shown
VisibleChanged
Form Load event only gets fired before the form is shown for the first time.
You should use a different event, like maybe Form Activated or GotFocus.
That's a normal behaviour. Load is for load form, not for show. In your case you try to show hided form. If you want to use
form.Show()
than use not a
form.Hide()
but
form.Close()
UPD:
Code should be:
public partial class Form3 : Form
{
List<DataRow> drlist = new List<DataRow>();
DataTable dt = new DataTable();
public Form3()
{
InitializeComponent();
}
private void btnCancel_Click(object sender, EventArgs e)
{
this.Close();
}
private void btnNext_Click(object sender, EventArgs e)
{
ShowNext();
}
private void btnBack_Click(object sender, EventArgs e)
{
ShowPrev();
}
private void ShowNext()
{
Form4 formNext = new Form4();
formNext.Show();
this.Close();
}
private void ShowPrev()
{
Form2 formPrev = new Form2();
formPrev.Show();
this.Close();
}
private void Form3_Load(object sender, EventArgs e)
{
// blah blah.
}
}
But there is a problem with such colutions - you shouldn't close your main form.
Related
My main form opens child form. When the child form closes the parent form needs to perform some tasks. How the parent can know that the child form was closed.
I have a workaround - the hidden button and I invoke PerformeClick method when the child raises the closing event.
Is there any better (more correct) way of doing it?
Add a listener event for your main/parent form when you instantiate child form. Example below:
private void button1_Click(object sender, EventArgs e)
{
Form2 f2 = new Form2();
f2.CustomFormClosed += CloseListener;
f2.Show();
}
private void CloseListener(object sender, EventArgs e, string test)
{
Console.WriteLine(test);
}
Edited for Custom Delegates & Events
Form2 code:
public delegate void CustomFormClosedHandler(object semder, FormClosedEventArgs e, string text);
public event CustomFormClosedHandler CustomFormClosed;
private void Form2_FormClosed(object sender, FormClosedEventArgs e)
{
CustomFormClosed(sender, e, "Hello World!");
}
One way to do this is:
return DialogResult from FormClosing event handler of Form2
private void Form2_FormClosing(object sender, FormClosingEventArgs e)
{
this.DialogResult = DialogResult.OK;
}
Run modal ShowDialog() on a new thread from Form1 and wait for the DialogResult
private void button2_Click(object sender, EventArgs e)
{
Form2 f2 = new Form2();
System.Threading.Tasks.Task.Run(() =>
{
if (f2.ShowDialog() == DialogResult.OK)
{
// do here whatever you want to do
MessageBox.Show("Form2 closed");
}
});
}
All you have to do:
1: Add public static method in the parent form:
public static void ChildFromClosed()
{
//Inform here
MessageBox.Show("Child form is closed!");
}
2: Add a (FormClosed) event in the child form that calls that method from the parent form:
private void frmChild_FormClosed(object sender, FormClosedEventArgs e)
{
//calling the static method in Parents form
frmParent.ChildFromClosed();
}
When I click a button a form is opened, but if the form is already open, then the app should display the message "Form already open!" and do nothing else.
My problem is, once I close the window [x] I can't open the form again.
Here's the code:
Form2 decript_form = new Form2();
private void button2_Click(object sender, EventArgs e)
{
if (!decript_form.Visible)
decript_form.Show();
else
MessageBox.Show("Form already open!");
}
When the "Close" button is pressed, you want it to just "hide" the form...you need to use e.Cancel to stop it going on and closing.
If you really really want to close the Form2 window instead of hiding it while your application is running....then call ReallyClose....so that the close isn't prevent (then create a new decript_form or null it out).
(Alternatively decript_form.Dispose() would force real closure too)
public partial class Form2 : Form
{
private bool m_bReallyClose = false;
public Form2()
{
InitializeComponent();
}
private void Form2_Load(object sender, EventArgs e)
{
}
private void Form2_FormClosing(object sender, FormClosingEventArgs e)
{
if (!m_bReallyClose)
{
this.Visible = false;
e.Cancel = true;
}
}
public void ReallyClose()
{
m_bReallyClose = true;
this.Close();
}
}
public partial class Form1 : Form
{
Form2 decript_form = new Form2();
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
if (!decript_form.Visible)
decript_form.Show();
else
MessageBox.Show("Form already open!");
}
private void button2_Click(object sender, EventArgs e)
{
decript_form.Dispose(); // or .ReallyClose();
decript_form = new Form2();
}
}
I assume that you talk about the [x] on Form2 being pressed. It that's the case you should handle the Closing event in Form2() and add
this.Hide();
to the handler. Even a closed window is still 'shown' until it is hidden.
class Form2
{
override protected void OnClosing(CancelEventArgs e)
{
Hide();
}
}
I have a couple of forms.
Let's call them mainForm, formA and formB.
On mainForm, there's a button that goes to formA and the button that does that has this bit of code:
private void buttonOpenFormA_Click(object sender, EventArgs e)
{
formA displayformA = new formA();
displayformA.Show();
this.Hide();
}
And on formA, I have another button that opens formB like this:
private void buttonOpenFormB_Click(object sender, EventArgs e)
{
formB displayformB = new formB();
displayformB.Show();
this.Hide();
}
And to return to mainForm:
private void buttonGoBack_Click(object sender, EventArgs e)
{
mainForm displayMainForm = new mainForm();
displayMainForm.Show();
this.Close();
}
And on formA, this works beautifully. But on formB, however, this same block of code refuses to show the mainForm. What am I doing wrong?
I think you can simple pass your MainForm Object to FormA then FormA to FormB then on click of button you should simple show your FormA object.
As per your code, you are here showing new MainForm object which is not you have created first time as you are creating new object in buttonGoBack_Click event.
You should need to make change in FormA
public MainForm mainForm {get;set;}
public FormA(MainForm mainForm)
{
this.mainForm= mainForm;
}
You should need to make change in FormB
public MainForm mainForm {get;set;}
public FormB(MainForm mainForm)
{
this.mainForm= mainForm;
}
private void buttonOpenFormA_Click(object sender, EventArgs e)
{
formA displayformA = new formA(this);
displayformA.Show();
this.Hide();
}
private void buttonOpenFormB_Click(object sender, EventArgs e)
{
formB displayformB = new formB(this.mainForm);
displayformB.Show();
this.Hide();
}
private void buttonGoBack_Click(object sender, EventArgs e)
{
(this.mainform as MainForm).Show();
this.Close();
}
Main Form.cs
private void buttonOpenFormA_Click(object sender, EventArgs e){
formA displayformA = new formA();
displayformA.ShowDialog();
//to close the form
this.dialogResult=DialogResult.OK;
}
FormA.cs
private void buttonOpenFormB_Click(object sender, EventArgs e){
formB displayformB = new formB();
displayformB.ShowDialog();
//to close the form
this.dialogResult=DialogResult.OK;
}
private void buttonGoBack_Click(object sender, EventArgs e){
//to close the form
this.DialogResult = System.Windows.Forms.DialogResult.OK;
}
You only need to use ShowDialog(). Whenever you want to close,use this.DialogResult=DialogResult.OK.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
I would like to control Form1 from Form2
I'm a newbie to C# and I can't find the answer I'm looking for in google, so I'm hoping someone here could help me. I'm only practicing to transfer data (or pass, call it however you want) from a form to another.
Here's what I have:
I have 2 forms - Form1 and Form2.
Form1 contains a textbox (named txtForm1) and a button (named btnForm1).
Form2 contains a textbox (named txtForm2) and a button (named btnForm2).
After running the application, by clicking the button btnForm1, the user opens Form2. The text that the user writes in the textbox (txtForm2) should be transfered to the textbox (txtForm1, which button is disabled) in Form1.
How can I do this transfer?
Edited:
Okay i need to be clear that this is all the code i have:
Form1 (button which opens Form2):
private void btnForm1_Click(object sender, EventArgs e)
{
new Form2().Show();
}
Form2 (button which closes Form2):
private void btnForm2_Click(object sender, EventArgs e)
{
this.Close();
}
I have NOTHING ELSE. (I'm a total newbie)
Make a public variable and pass it the value from your text box and then onto your second form.
public static string myVar;
myVar = txtForm2.Text;
and when you return to the first form:
txtForm1.Text = Form2.myVar;
In your Form2 you should have some like:
private void btnForm2_Click(object sender, EventArgs e)
{
this.Hide();
}
public String GettxtForm2()
{
return txtForm2.Text;
}
Now in form1 you can acces that txtForm2 with something like:
Form2 form2 = new Form2();
//on click btnForm1 show that form2 where you can edit the txtForm2
private void btnForm1_Click(object sender, EventArgs e)
{
form2.Show();
}
//after you save the txtForm2 when you will focus back to form1 the txtForm1 will get the value from txtForm2
private void Form1_Enter(object sender, EventArgs e)
{
txtForm1.Text = Form2.GettxtForm2();
}
You can easy modify the events where all this logic can occur...
in Form1:
public void SetTextboxText(String text)
{
txtForm1.Text = text;
}
private void btnForm1_Click(object sender, EventArgs e)
{
var frm = new Form2(this); // pass parent form (this) in constructor
frm.Show();
}
in Form2:
Form _parentForm;
public Form2(Form form)
{
_parentForm = form;
}
private void txtForm2_TextChanged(object sender, EventArgs e)
{
_parentForm.SetTextboxText(txtForm2.Text); // change Form1.txtForm1.Text
}
Try this ;)
On Form1:
private void button1_Click(object sender, EventArgs e)
{
Form2 frm2 = new Form2(textBox1.Text);
frm2.Show();
this.Hide();
}
On form2:
public partial class Form2 : Form
{
public string textBoxValue;
public Form2()
{
InitializeComponent();
}
public Form2(string textBoxValue)
{
InitializeComponent();
this.textBoxValue = textBoxValue;
}
private void Form2_Load(object sender, EventArgs e)
{
textBox2.Text = textBoxValue;
}
Basically; Form1 has 2 buttons, Form2 has 1 button.
When you click Form2's button it checks which button on Form1 you clicked, opening Form3 or Form4 depending on which button you clicked (on Form1).
So I've utilized Mark Halls first method of passing variables between forms. Now for the second half of my closed refinement.
Form1
private void btnLogin_Click(object sender, EventArgs e)
{
// Call function while storing variable info.
Account("login");
}
private void btnRegister_Click(object sender, EventArgs e)
{
// Call function while storing variable info.
Account("register");
}
// Function used to pass Variable info to Account form while opening it as instance.
private void Account(string formtype)
{
// Generate/Name new instant of form.
frontend_account frmAcc = new frontend_account();
// Pass variable to instance.
frmAcc.CheckButtonClick = formtype;
// Show form instance.
frmAcc.Show(this);
// Hide this instance.
this.Hide();
}
Form2
// String Variable to store value from Login.
public string CheckButtonClick { get; set; }
private void btnContinue_Click(object sender, EventArgs e)
{
// If statement to open either Main form or Registration form, based on Login variable.
if (CheckButtonClick == "login")
{
// Generate/Name new instant of form.
frontend_main frmMain = new frontend_main();
// Show form instant.
frmMain.Show();
// Close this instant.
this.Close();
}
else if (CheckButtonClick == "register")
{
// Generate/Name new instant of form.
frontend_register frmReg = new frontend_register();
// Show form instant.
frmReg.Show();
// Close this instant.
this.Close();
}
}
On Form2 there are TWO radio buttons, can I adept that code to set the focus of a tab control when a form is opened? ie. if radClient is checked set focus on tabcontrol after opening winform, else if radStudent is checked set focus on tabcontrol (other page) after opening winform... and i guess don't open a winform if no radio is checked.
I believe this will set the focus;
// Sets focus to first tab.
tabRegister.SelectedTab = tabRegister.TabPages[0];
// Sets focus to second tab.
tabRegister.SelectedTab = tabRegister.TabPages[1];
In your example the first problem I see is you are closing your parent form which closes your Form1 and disposes of Your Form2, What I would do is Hide Form1 instead of Closing it, I would then create a public property on Form2 to pass in the Button that was selected. But anytime you are opening and closing multiple Forms it can get messy, what I would do would be to create UserControls for your additional Forms and swap them out in a Panel. The first example is how to do it the way that you asked.
Form
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnLogin_Click(object sender, EventArgs e)
{
ShowForm2("login");
}
private void btnRegister_Click(object sender, EventArgs e)
{
ShowForm2("register");
}
private void ShowForm2(string formtype)
{
Form2 f2 = new Form2(); // Instantiate a Form2 object.
f2.CheckButtonClick = formtype;
f2.Show(this); // Show Form2 and
this.Hide(); // closes the Form1 instance.
}
}
Form2
ublic partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
public string CheckButtonClick { get; set; }
private void button1_Click(object sender, EventArgs e)
{
if (CheckButtonClick == "login")
{
Form3 f3 = new Form3(); // Instantiate a Form3 object.
f3.Show(); // Show Form3 and
this.Close(); // closes the Form2 instance.
}
else if (CheckButtonClick == "register")
{
Form4 f4 = new Form4(); // Instantiate a Form4 object.
f4.Show(); // Show Form4 and
this.Close(); // closes the Form2 instance.
}
}
}
Form3 and Form4 note since Form1 is long forgotten to these forms I search for it to Open back up
public partial class Form3 : Form
{
public Form3()
{
InitializeComponent();
}
private void Form3_FormClosed(object sender, FormClosedEventArgs e)
{
FormCollection frms = Application.OpenForms;
foreach (Form f in frms)
{
if (f.Name == "Form1")
{
f.Show();
break;
}
}
}
}
The second Option with UserControls has one Form with a Panel on it. It uses events to signal the Form to Change Controls plus a public property on UserControl2
public partial class Form1 : Form
{
string logonType;
public Form1()
{
InitializeComponent();
}
private void userControl1_LoginOrRegisterEvent(object sender, LoginOrRegisterArgs e)
{
logonType = e.Value;
userControl2.BringToFront();
}
private void userControl2_ControlFinshedEvent(object sender, EventArgs e)
{
if (logonType == "logon")
userControl3.BringToFront();
else if (logonType == "register")
userControl4.BringToFront();
}
private void userControl3_ControlFinshedEvent(object sender, EventArgs e)
{
userControl1.BringToFront();
}
private void userControl4_ControlFinshedEvent(object sender, EventArgs e)
{
userControl1.BringToFront();
}
}
UserControl1
public partial class UserControl1 : UserControl
{
public delegate void LoginOrRegisterHandler(object sender, LoginOrRegisterArgs e);
public event LoginOrRegisterHandler LoginOrRegisterEvent;
public UserControl1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
LoginOrRegisterArgs ea = new LoginOrRegisterArgs("logon");
LoginOrRegisterEvent(sender, ea);
}
private void button2_Click(object sender, EventArgs e)
{
LoginOrRegisterArgs ea = new LoginOrRegisterArgs("register");
LoginOrRegisterEvent(sender, ea);
}
}
public class LoginOrRegisterArgs
{
public LoginOrRegisterArgs(string s) {Value = s;}
public string Value {get; private set;}
}
UserControl2
public partial class UserControl2 : UserControl
{
public delegate void ControlFinishedHandler(object sender, EventArgs e);
public event ControlFinishedHandler ControlFinshedEvent;
public UserControl2()
{
InitializeComponent();
}
public string SetLogonType { get; set; }
private void button1_Click(object sender, EventArgs e)
{
ControlFinshedEvent(sender, new EventArgs());
}
}
UserControl3 & UserControl4 exactly the same except for different Class Name
public partial class UserControl3 : UserControl
{
public delegate void ControlFinishedHandler(object sender, EventArgs e);
public event ControlFinishedHandler ControlFinshedEvent;
public UserControl3()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
ControlFinshedEvent(sender, new EventArgs());
}
}
As I suggested in my comment, one of the best way I know to pass data between forms is to use events.
Basically, in the "child" forms, you declare an event that will be handled, or listened to, by the "main" form.
See the referenced answer from my comment, and if you have specific questions on how to adapt it, ask away.
Cheers