Opening a previous form when one is closed - c#

First of all, I am a newcomer to C# and programming in general. I've searched pretty thoroughly, but I can only find instances where someone wants to open another form and hide the one that the button was pressed on.
In this instance, I'm having issues with my program continuously running when I press the (X) on any form other than the main "Form1".The form-to-form navigation works fine. i.e.: clicking a button hides the main window and opens the appropriate form, and the "back" button on that form hides itself and shows (I guess another instance) of the previous "main" form. --I could probably use some guidance in that, too. lol
I wouldn't mind if it closed the entire application if the X was pressed, but I need to have the "X" present on all windows and all windows need to exit the entire app if the X is pressed. Any suggestions?
Thanks in advance,
Code:
Form1:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public void btnTransaction_Click(object sender, EventArgs e)
{
Transaction transactionForm = new Transaction();
Form mainForm = this;
transactionForm.Show();
mainForm.Hide();
}
}
Transaction Form:
public partial class Transaction : Form
{
public Transaction()
{
InitializeComponent();
}
private void button4_Click(object sender, EventArgs e)
{
Form1 mainForm = new Form1(); //not sure if I'm doing this right..
this.Hide(); //I don't know how to "reuse" the original Form1
mainForm.Show();
}
}

I would recommend you create an MDI Container for this. Drag and drop a MenuStrip from the ToolBox to Form1 and then create a ToolStripMenuItem "form2" in MenuStrip.
Now you can call your form2 in form1 like this
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
IsMdiContainer = true;
}
Form2 frm2;
public void CreateMdiChild<T>(ref T t) where T : Form, new()
{
if (t == null || t.IsDisposed)
{
t = new T();
t.MdiParent = this;
t.Show();
}
else
{
if (t.WindowState == FormWindowState.Minimized)
{
t.WindowState = FormWindowState.Normal;
}
else
{
t.Activate();
}
}
}
private void form2ToolStripMenuItem_Click(object sender, EventArgs e)
{
CreateMdiChild<Form2>(ref frm2);
}
}
When by clicking ToolStripMenuItem you fire ToolStripmenuItem event , it will show Form2 as child in form1 i.e the mdi container and will be closed when you close form1.

public partial class Transaction : Form
{
Form1 _mainForm;
public Transaction(Form1 mainForm)
{
InitializeComponent();
_mainForm = mainForm;
}
private void button4_Click(object sender, EventArgs e)
{
this.Close(); //since you always create a new one in Form1
_mainForm.Show();
}
}

You can use the use Form.ShowDialog()
When this method is called, the code following (code below the 'ShowDialog()') it is not executed until after the dialog box is closed.
private void button4_Click(object sender, EventArgs e)
{
Form1 mainForm = new Form1();
this.Hide();
mainForm.ShowDialog();
this.Show();
}

You could use the ShowDialog() method that will require the user to interact with the new form before returning to the previous form. For instance you could try this:
public void btnTransaction_Click(object sender, EventArgs e)
{
using (var transactionForm = new Transaction())
{
this.Hide();
if (transactionForm.ShowDialog() == DialogResult.OK)
{
this.Show();
}
}
}
The DialogResult is something you can set on the TransactionForm like so:
private void button4_Click(object sender, EventArgs e)
{
this.DialogResult = DialogResult.OK;
this.Close();
}
That's a pretty standard way of forcing interaction on a new form.

protected override void OnClosing(CancelEventArgs e)
{
this.Hide();
menu menu = new menu("administrator");
menu.ShowDialog();
this.Close();
}
//happy coding

Related

visual studio c# copy data to another form [duplicate]

I want to pass values between two Forms (c#). How can I do it?
I have two forms: Form1 and Form2.
Form1 contains one button. When I click on that button, Form2 should open and Form1 should be in inactive mode (i.e not selectable).
Form2 contains one text box and one submit button. When I type any message in Form2's text box and click the submit button, the Form2 should close and Form1 should highlight with the submitted value.
How can i do it? Can somebody help me to do this with a simple example.
There are several solutions to this but this is the pattern I tend to use.
// Form 1
// inside the button click event
using(Form2 form2 = new Form2())
{
if(form2.ShowDialog() == DialogResult.OK)
{
someControlOnForm1.Text = form2.TheValue;
}
}
And...
// Inside Form2
// Create a public property to serve the value
public string TheValue
{
get { return someTextBoxOnForm2.Text; }
}
private void button1_Click(object sender, EventArgs e)
{
Form2 frm2 = new Form2(textBox1.Text);
frm2.Show();
}
public Form2(string qs)
{
InitializeComponent();
textBox1.Text = qs;
}
Define a property
public static class ControlID {
public static string TextData { get; set; }
}
In the Form1
private void button1_Click(object sender, EventArgs e)
{
ControlID.TextData = txtTextData.Text;
}
Getting the data in Form1 and Form2
private void button1_Click(object sender, EventArgs e)
{
string text= ControlID.TextData;
}
After a series of struggle for passing the data from one form to another i finally found a stable answer. It works like charm.
All you need to do is declare a variable as public static datatype 'variableName' in one form and assign the value to this variable which you want to pass to another form and call this variable in another form using directly the form name (Don't create object of this form as static variables can be accessed directly) and access this variable value.
Example of such is,
Form1
public static int quantity;
quantity=TextBox1.text; \\Value which you want to pass
Form2
TextBox2.Text=Form1.quantity;\\ Data will be placed in TextBox2
Declare a public string in form1
public string getdata;
In button of form1
form2 frm= new form2();
this.hide();
form2.show();
To send data to form1 you can try any event and code following in that event
form1 frm= new form1();
form1.getdata="some string to be sent to form1";
Now after closing of form2 and opening of form1, you can use returned data in getdata string.
I've worked on various winform projects and as the applications gets more complex (more dialogs and interactions between them) then i've started to use some eventing system to help me out, because management of opening and closing windows manually will be hard to maintain and develope further.
I've used CAB for my applications, it has an eventing system but it might be an overkill in your case :) You could write your own events for simpler applications
Form1 Code :
private void button1_Click(object sender, EventArgs e)
{
Form2 f2 = new Form2();
f2.ShowDialog();
MessageBox.Show("Form1 Message :"+Form2.t.Text); //can put label also in form 1 to show the value got from form2
}
Form2 Code :
public Form2()
{
InitializeComponent();
t = textBox1; //Initialize with static textbox
}
public static TextBox t=new TextBox(); //make static to get the same value as inserted
private void button1_Click(object sender, EventArgs e)
{
this.Close();
}
It Works!
declare string in form1
public string TextBoxString;
in form1 click event add
private void button1_Click(object sender, EventArgs e)
{
Form1 newform = new Form1();
newform = this;
this.Hide();
MySecform = new Form2(ref newform);
MySecform.Show();
}
in form2 constructer
public Form2(ref Form1 form1handel)
{
firstformRef = form1handel;
InitializeComponent();
}
in form2 crate variable Form1 firstformRef;
private void Submitt_Click(object sender, EventArgs e)
{
firstformRef.TextBoxString = textBox1.Text;
this.Close();
firstformRef.Show();
}
In this code, you pass a text to Form2. Form2 shows that text in textBox1.
User types new text into textBox1 and presses the submit button.
Form1 grabs that text and shows it in a textbox on Form1.
public class Form2 : Form
{
private string oldText;
public Form2(string newText):this()
{
oldText = newText;
btnSubmit.DialogResult = DialogResult.OK;
}
private void Form2_Load(object sender, EventArgs e)
{
textBox1.Text = oldText;
}
public string getText()
{
return textBox1.Text;
}
private void textBox1_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
DialogResult = System.Windows.Forms.DialogResult.OK;
}
}
}
And this is Form1 code:
public class Form1:Form
{
using (Form2 dialogForm = new Form2("old text to show in Form2"))
{
DialogResult dr = dialogForm.ShowDialog(this);
if (dr == DialogResult.OK)
{
tbSubmittedText = dialogForm.getText();
}
dialogForm.Close();
}
}
Ok so Form1 has a textbox, first of all you have to set this Form1 textbox to public in textbox property.
Code Form1:
Public button1_click()
{
Form2 secondForm = new Form2(this);
secondForm.Show();
}
Pass Form1 as this in the constructor.
Code Form2:
Private Form1 _firstForm;
Public Form2(Form1 firstForm)
{
_firstForm = firstForm:
}
Public button_click()
{
_firstForm.textBox.text=label1.text;
This.Close();
}
you can pass as parameter the textbox of the Form1, like this:
On Form 1 buttom handler:
private void button2_Click(object sender, EventArgs e)
{
Form2 newWindow = new Form2(textBoxForReturnValue);
newWindow.Show();
}
On the Form 2
public static TextBox textBox2; // class atribute
public Form2(TextBox textBoxForReturnValue)
{
textBox2= textBoxForReturnValue;
}
private void btnClose_Click(object sender, EventArgs e)
{
textBox2.Text = dataGridView1.CurrentCell.Value.ToString().Trim();
this.Close();
}
Constructors are the best ways to pass data between forms or Gui Objects you can do this.
In the form1 click button you should have:
Form1.Enable = false;
Form2 f = new Form2();
f.ShowDialog();
In form 2, when the user clicks the button it should have a code like this or similar:
this.Close();
Form1 form = new Form1(textBox1.Text)
form.Show();
Once inside the form load of form 1 you can add code to do anything as you get the values from constructor.
How to pass the values from form to another form
1.) Goto Form2 then Double click it. At the code type this.
public Form2(string v)
{
InitializeComponent();
textBox1.Text = v;
}
2.) Goto Form1 then Double click it. At the code type this.
//At your command button in Form1
private void button1_Click(object sender, EventArgs e)
{
Form2 F2 = new Form2(textBox1.Text);
F2.Show();
}
This is very simple.
suppose you have 2 window form Form1 and Form2 and you want to send record of textbox1 from Form1 to Form2 and display this record in label1 of Form2;
then in Form2 create a label which name is label1 and go to the property of label1 and set 'Modifiers'=public and in Form one create a textBox with id textBox1 and a button of name submit then write the following code on button click event
button1_Click(object sender, EventArgs e)
{
Form2 obj=new Form2();
obj.label1.text=textBox1.text.ToString();
obj.show();
}
thats it...
for this way you can bind dataset record to another form's datagridview......
You can make use of a different approach if you like.
Using System.Action (Here you simply pass the main forms function as the parameter to the child form like a callback function)
OpenForms Method ( You directly call one of your open forms)
Using System.Action
You can think of it as a callback function passed to the child form.
// -------- IN THE MAIN FORM --------
// CALLING THE CHILD FORM IN YOUR CODE LOOKS LIKE THIS
Options frmOptions = new Options(UpdateSettings);
frmOptions.Show();
// YOUR FUNCTION IN THE MAIN FORM TO BE EXECUTED
public void UpdateSettings(string data)
{
// DO YOUR STUFF HERE
}
// -------- IN THE CHILD FORM --------
Action<string> UpdateSettings = null;
// IN THE CHILD FORMS CONSTRUCTOR
public Options(Action<string> UpdateSettings)
{
InitializeComponent();
this.UpdateSettings = UpdateSettings;
}
private void btnUpdate_Click(object sender, EventArgs e)
{
// CALLING THE CALLBACK FUNCTION
if (UpdateSettings != null)
UpdateSettings("some data");
}
OpenForms Method
This method is easy (2 lines). But only works with forms that are open.
All you need to do is add these two lines where ever you want to pass some data.
Main frmMain = (Main)Application.OpenForms["Main"];
frmMain.UpdateSettings("Some data");
I provided my answer to a similar question here
You can use this;
Form1 button1 click
private void button1_Click(object sender, EventArgs e)
{
Form2 frm2 = new Form2();
this.Hide();
frm2.Show();
}
And add this to Form2
public string info = "";
Form2 button1 click
private void button1_Click(object sender, EventArgs e)
{
info = textBox1.Text;
this.Hide();
BeginInvoke(new MethodInvoker(() =>
{
Gogo();
}));
}
public void Gogo()
{
Form1 frm = new Form1();
frm.Show();
frm.Text = info;
}
if you change Modifiers Property of a control in a Form to Public, another Forms can access to that control.
f.e. :
Form2 frm;
private void Form1_Load(object sender, EventArgs e)
{
frm = new Form2();
frm.Show();
}
private void button1_Click(object sender, EventArgs e)
{
MessageBox.Show(frm.txtUserName.Text);
//txtUserName is a TextBox with Modifiers=Public
}
// In form 1
public static string Username = Me;
// In form 2's load block
string _UserName = Form1.Username;
the tag Properties receive object value
( C# send value to another form )
private void btn_Send_Click(object sender, EventArgs e)
{
Form frm = new formToSend();
frm.tag = obj;
frm.ShowDialog();
}
Receive value that sent from previous form ( frm )
Ex: sent data is string ( we need to type casting first, because tag value is an object )
public Receive_Form()
{
InitializeComponent();
MessageBox.Show((string)this.Tag);
}
How about using a public Event
I would do it like this.
public class Form2
{
public event Action<string> SomethingCompleted;
private void Submit_Click(object sender, EventArgs e)
{
SomethingCompleted?.Invoke(txtData.Text);
this.Close();
}
}
and call it from Form1 like this.
private void btnOpenForm2_Click(object sender, EventArgs e)
{
using (var frm = new Form2())
{
frm.SomethingCompleted += text => {
this.txtData.Text = text;
};
frm.ShowDialog();
}
}
Then, Form1 could get a text from Form2 when Form2 is closed
Thank you.

How to pause processing code till the form hides in C#?

I am new to C# and I am using windows forms.
I have form1 and form2, I show and hide form2 from form1 as following:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
Form2 frm2 = new Form2();
private void button_showForm2_Click(object sender, EventArgs e)
{
frm2.Show();
//I want to show the following message once form2 hides:
MessageBox.Show("Form2 is hidden. Continue processing next line of code");
}
}
In form2:
private void button_HideForm2_Click(object sender, EventArgs e)
{
Hide();
}
When I run the above code and show form2, form2 shows up with the messageBox at same time. I know it is because when using Show() method it does not hold the program flow and continue executing next lines of code while using ShowDialog() holds the program flow till you close the child form.
What I want to do is ( I do not want to use ShowDialog()) : I want to show form2 and when you finish using it and hide it I want to display the above message (in form1) when form2 hides.
Anyone knows how can I do that? Thank you alot.
I would implement it in this way
Form1:
private void button_showForm2_Click(object sender, EventArgs e)
{
this.frm2 = new Form2(this);
this.frm2.Show();
}
public void ShowMessage()
{
MessageBox.Show("Form2 is hidden. Continue processing next line of code");
}
Form2:
public Form1 _Form1 { get; private set; }
public Form2(Form1 _Form1) { this._Form1 = _Form1; }
private void button_HideForm2_Click(object sender, EventArgs e)
{
Hide();
this._Form1.ShowMessage();
}
Hook the Form's VisibleChanged Event, your code will then get fired when the Forms visibility changes.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
Form2 frm2 = new Form2();
private void button_showForm2_Click(object sender, EventArgs e)
{
frm2.VisibleChanged += new EventHandler(this.FormVisibilityChanged);
frm2.Show();
}
private void FormVisibilityChanged(object sender, EventArgs e)
{
frm2.VisibleChanged -= new EventHandler(this.FormVisibilityChanged);
MessageBox.Show("Form2 is hidden. Continue processing next line of code");
}
}

Switching between between main and pop-up form

How can I lock (and make it look faded) a parent form while the child form is active? I tried to make the child form topmost but that just made it always visible and I can still edit the parent form. I want to be unable to operate on the main form while the child form is running in VS2012, C#. This is the code I used to call the second form...
private void checkButton_Click(object sender, EventArgs e)
{
Form2 newForm = new Form2(this);
newForm.Show();
}
One very simple way is to use ShowDialog() instead of Show() on the child form. This will prevent any interaction with the main form. This is also a neat way of passing back results. There are many other ways, of course.
Example:
private void checkButton_Click(object sender, EventArgs e)
{
Form2 newForm = new Form2(this);
newForm.ShowDialog();
}
See MSDN for further details: https://msdn.microsoft.com/en-us/library/c7ykbedk(v=vs.110).aspx
Just add Hide() for Current Running Form,
private void checkButton_Click(object sender, EventArgs e)
{
Form2 newForm = new Form2(this);
this.Hide();//hide old form
newForm.Show();
}
You can use Form.ShowDialog to create dialog which will open on top of parent form and will not allow to edit parent until you close child
private void checkButton_Click(object sender, EventArgs e)
{
Form2 newForm = new Form2(this);
newForm.ShowDialog(this);
}
You might wanna run the form2 in separate thread and set topmost = true, the form1 will function unblocked, but the form2 will run whatever you want unblocked too. Is this what you want?
namespace TestModal
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Thread thrd = new Thread(newwindow);
thrd.IsBackground = true;
thrd.Start();
}
private void newwindow()
{
Form2 frm2 = new Form2();
frm2.TopMost = true;
frm2.ShowDialog();
}
}
}

How to switch between forms without creating new instance of forms?

in my application i have four forms form1 form2 form3 form4 .and each form have two buttons i.e next and previous buttons to switch between forms .and my question is how can i Switch between forms without creating new instance of forms? below is my code
In Form1:
public Form1()
{
InitializeComponents();
}
private void Next_Click(object sender, EventArgs e)
{
this.Hide()
Form2 form2 = new Form2();
form2.Show();
}
In Form2:
public Form2()
{
InitializeComponents();
}
private void Previous_Click(object sender, EventArgs e)
{
this.Hide();
Form1 form1 = new Form1();
form1.Show();
}
private void Next_Click(object sender, EventArgs e)
{
this.Hide();
Form3 form3 = new Form3();
form3.Show();
}
In Form3:
public Form3()
{
InitializeComponents();
}
private void Previous_Click(object sender, EventArgs e)
{
this.Hide();
Form2 form2 = new Form2();
form2.Show();
}
private void Next_Click(object sender, EventArgs e)
{
this.Hide();
Form4 form4 = new Form4();
form4.Show();
}
In Form4:
public Form4()
{
InitializeComponents();
}
private void Previous_Click(object sender, EventArgs e)
{
this.Hide();
Form3 form3 = new Form3();
form3.Show();
}
In Main:
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
In above code i am creating new instances of forms every time..,How can i Avoid this and How can i Switch between forms without creating new instances of forms.... please help me
Since you are accessing your forms sequentially just make sure that you use the Show Method that assigns the owner to the created Form and assign it to a class level variable after you create it. Something like this should work for you.
Form1
public partial class Form1 : Form
{
Form2 frm2;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
if (frm2 == null)
{
frm2 = new Form2(); //Create form if not created
frm2.FormClosed += frm2_FormClosed; //Add eventhandler to cleanup after form closes
}
frm2.Show(this); //Show Form assigning this form as the forms owner
Hide();
}
void frm2_FormClosed(object sender, FormClosedEventArgs e)
{
frm2 = null; //If form is closed make sure reference is set to null
Show();
}
}
Form2
public partial class Form2 : Form
{
Form3 frm3;
public Form2()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Owner.Show(); //Show the previous form
Hide();
}
private void button2_Click(object sender, EventArgs e)
{
if (frm3 == null)
{
frm3 = new Form3();
frm3.FormClosed += frm3_FormClosed;
}
frm3.Show(this);
Hide();
}
void frm3_FormClosed(object sender, FormClosedEventArgs e)
{
frm3 = null;
Show();
}
}
Form3
public partial class Form3 : Form
{
public Form3()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Owner.Show();
Hide();
}
}
May be a easy solution. You can make a class that contains static object of all forms that you need. So you will be able to access all these forms from any forms of your choice and the good thing is they are initialized once.
public class formList
{
private static Form1 _form1 = new Form1();
public static Form1 form1 { get {return _form1;}
.................
............
}
Try This:
Form1 myForm =(Form1) Application.OpenForms["Form1"];
myForm.Show();
You can check if the form of interest exists, and if not create it:
public static T OpenOrCreateForm<T>()
where T: Form, new() {
T result;
// Test if form exists
foreach(Form form in Application.OpenForms) {
result = form as T;
if (!Object.ReferenceEquals(null, result)) {
// Form found; and this is the right place
// to restore form size,
// bring form to front etc.
if (result.WindowState == FormWindowState.Minimized)
result.WindowState = FormWindowState.Normal;
result.BringToFront();
return result;
}
}
// Form doesn't exist, let's create it
result = new T();
// Probably, you want to show the created form
result.Show();
resturn result;
}
...
private void Previous_Click(object sender, EventArgs e)
{
Hide();
OpenOrCreateForm<Form1>();
}
private void Next_Click(object sender, EventArgs e)
{
Hide();
OpenOrCreateForm<Form3>();
}
public bool IsFormAlreadyOpen(Type FormType)
{
foreach (Form OpenForm in Application.OpenForms)
{
if (OpenForm.GetType() == FormType)
return true;
}
return false;
}
This function can be used to find out whether a form is already opened or not
call IsFormAlreadyOpen(Form4) if it returns true which means Form4 is already opened
and in your case
in every forms constructor() create next and previous forms object
and in the button click calls IsFormAlreadyOpen() to find out whether the form is already opened or not and if it already opened just bring that form in front
other wise display the form using obj.show() method
and hide or close the parent form
Looks like you are trying to achieve wizard like feature. I would recommend having a single form. Then, add a customized tab control to it. Add buttons to form that moves previous and next.
To customize tab control, this is what you need to do:
public class CustomWizard : TabControl
{
/// <summary>
/// This method traps windows message and hides other tabs in the tab control.
/// Message trapped: TCM_ADJUSTRECT
/// </summary>
/// <param name="m">Reference to Windows message</param>
protected override void WndProc(ref Message m)
{
// Second condition is to keep tab pages visible in design mode
if (m.Msg == 0x1328 && !DesignMode)
{
m.Result = (IntPtr)1;
}
else
{
base.WndProc(ref m);
}
}
/// <summary>
/// This method traps the press to stop users from selecting tab page via keyboard
/// </summary>
/// <param name="ke">Event details</param>
protected override void OnKeyDown(KeyEventArgs ke)
{
if (ke.Control && ke.KeyCode == Keys.Tab)
return;
base.OnKeyDown(ke);
}
private void InitializeComponent()
{
this.SuspendLayout();
this.ResumeLayout(false);
}
}
This tab control will only display one tab at a time. Although, at design time you can see them all. Add this and buttons to your form. On button click, merely set the SelectedIndex property of this tab control.
I had the same issue. An application I needed that had many forms and I needed to switch between forms forward n backward without losing the data. I came up with the following solution and it worked for me.
In the main (Program.cs) file, write the following two classes:
static class Variables
{
public static DataSet Configurations = new DataSet();
public static float ExchangeRate = 0;
public static Dictionary<string, int> ItemsCategories = new Dictionary<string, int>();
public static Dictionary<string, float> WeightUnits = new Dictionary<string, float>();
}
static class Forms
{
public static Form2 F_Form2 = new Form2();
public static Form3 F_Form3 = new Form3();
}
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
///
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
The first class is used for Global variables that can be used across the forms. You can access any variable by:
Variables.ExchangeRate = 7.2; //(for ex).
The second class is where you define new instance of all your forms. You can hide n show them anywhere across all the forms by:
Forms.F_Form3.Show();
or
Forms.F_Form2.Hide();
This works smoothly and perfect for me. Try it.
Just remove the this.hide() in the first form and the [formNameHere].show(); in the second form.
Like this:
Form 1:
public Form1()
{
InitializeComponents();
}
private void Next_Click(object sender, EventArgs e)
{
this.Hide()
Form2 form2 = new Form2();
form2.Show();
}
Form 2:
public Form2()
{
InitializeComponents();
}
private void Previous_Click(object sender, EventArgs e)
{
Form1 form1 = new Form1();
this.Hide();
}
private void Next_Click(object sender, EventArgs e)
{
Form3 form3 = new Form3();
this.Hide();
}
etc.. not good at explaining, and with C# really. But this should work.
//In Form1
private static Form1 i_Instance = null;
public static Form1 Instance
{
get
{
if (Form1.i_Instance == null) Form1.i_Instance = new Form1();
return Form1.i_Instance;
}
}
// And instantiation in other forms shall look like following
Form1 F1 = Form1.Instance;
F1.Show();

Passing values between forms; Refining

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

Categories

Resources