Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I have a NewForm and I need it to do something in my main form when a button in my new form is clicked.
public Newform()
{
InitializeComponent();
}
private void cancel_Click(object sender, EventArgs e)
{
this.Close();
}
private void dontsave_click(object sender, EventArgs e)
{
}
}
}
I have a dontsave button and I need it to clear my textbox in my mainform when clicked and close the newform.
This will get you started:
using System;
using System.Windows.Forms;
// Form1 code.
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
Form2 frm2 = new Form2(); // Instantiate your form2 object.
public Form1()
{
InitializeComponent();
frm2.Show(); // Show the form.
}
private void button_save_Click(object sender, EventArgs e)
{
SaveFileDialog saveDlg = new SaveFileDialog();
saveDlg.ShowDialog(); // This shows a 'Save' dialog.
if (saveDlg.ShowDialog() == DialogResult.OK) // Capture user input from the dialog.
{
// do some work here
}
}
private void dontsave_Click(object sender, EventArgs e)
{
frm2.ClearTextBox(frm2); // Call the 'ClearTextBox' function from form2.
}
private void cancel_Click(object sender, EventArgs e)
{
this.Close(); // NOTE: Probably better to use Application.Exit() here.
}
}
}
//Form2 code.
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
public void ClearTextBox(Form form) // Pass a form as an overload.
{
textBox1.Text = ""; // Clear the textbox.
}
}
}
when you create your NewForm, you need to either:
1) Create an overload constructor to accept your parent form
2) have a public property which holds a reference to your parent form then finally show your NewForm
then when you are pressing the "dontsave" - simply reference the parent form and clear the textbox, and making sure the textbox property is either public or much preferably, a method call (dont give full access to a UI Control from other forms!)
I strongly recommend against blindly passing one Form into the constructor of another. Instead, expose some property events of the child form:
public Form1() {
var childForm = new ChildForm();
childForm.DontSave += // event handler
}
class ChildForm : Form {
public event EventHandler DontSave {
add { dontSaveButton.Click += value; }
remove { dontSaveButton.Click -= value; }
}
}
At MainForm.cs
public partial class MainForm : Form
{
NewForm frm2;
public MainForm()
{
InitializeComponent();
frm2 = new NewForm();
frm2.Show();
frm2.dontSaveButton += new DontSaveButtonHandler(frm2_dontSaveButton);
}
void frm2_dontSaveButton()
{
textBox1.Clear();
frm2.Close();
}
}
At NewForm.cs
public delegate void DontSaveButtonHandler();
public partial class NewForm : Form
{
public event DontSaveButtonHandler dontSaveButton;
public NewForm()
{
InitializeComponent();
}
private void btnDontSave_Click(object sender, EventArgs e)
{
if (dontSaveButton != null)
{
dontSaveButton();
}
}
}
I would guess my answer is what supposed to be. Using delegate is a good practice.
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
How to Create Control and Event from Out side the form C#
namespace MyProject
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
}
class Methods
{
//need to create method to Form 1 From herer
}
class EventHandler
{
//need to create EventHandler to Form 1 From herer
}
class CreateControl
{
//dynamically Create controls for Form1 From this class
}
}
Something like this, if I've understood you right:
Form myForm = ...
// Let's create a button on myForm
Button myButton = new Button() {
Text = "My Button", //TODO: specify all the properties required here
Size = new Size(75, 25),
Location = new Point(30, 40),
Parent = myForm, // Place on myForm instance
};
// We can implement an event with a help of lambda
myButton.Click += (s, ea) => {
//TODO: put relevant code here
};
While I don't see any benefit in doing so, this would be what you want:
namespace MyProject
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
Methods.Init(this);
}
}
class Methods
{
//need to create method to Form 1 From herer
public static void Init(Form frm)
{
frm.Controls.Add((new CreateControl()).CreateButton("Test"));
}
}
class EventHandlerWrapper
{
//need to create EventHandler to Form 1 From herer
private void button_Click(object sender, EventArgs e)
{
MessageBox.Show("TEST");
}
}
class CreateControl
{
public Button CreateButton(string text)
{
EventHandlerWrapper e = new EventHandlerWrapper();
Button btn = new Button();
btn.Text = text;
btn.Click += e.button_Click;
}
}
}
This question already has answers here:
Communicate between two windows forms in C#
(12 answers)
Closed 6 years ago.
I have two forms. Form1 has a label, Form2 has a button. I'm adding Form2 to Form1 as a control. When I click the button I want the label to update.
Code for Form1:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
RunTest();
}
private void RunTest()
{
Form myForm2 = new Form2();
myForm2.TopLevel = false;
this.Controls.Add(myForm2);
myForm2.Show();
}
public static void UpdateLabel()
{
label1.Text = "Button Pressed"; //ERROR
}
}
Code for Form2:
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Form1.UpdateLabel();
}
}
Calling the UpdateLabel() require it to be static, but then I can't update Label1.Text
Do you have any suggestions what I should do in this situation? I want to add many Form2 to Form1 when I get this to work.
In Form2 add a Property of Type Form1 and assign it with this from Form1.
private void RunTest()
{
Form myForm2 = new Form2();
myForm2.otherform = this; // <--- note this line
myForm2.TopLevel = false;
this.Controls.Add(myForm2); // TODO: why is this line here?
myForm2.Show();
}
You can then
private void button1_Click(object sender, EventArgs e)
{
otherform.UpdateLabel();
}
if you make UpdateLabel() non-static
public void UpdateLabel()
{
label1.Text = "Button Pressed";
}
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
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
This question already has answers here:
pass a value from one form to another
(7 answers)
Closed 4 years ago.
I am passing data between 2 windows forms in C#. Form1 is the main form, whose textbox will receive the text passed to it from form2_textbox & display it in its textbox (form1_textbox).
First, form1 opens, with an empty textbox and a button, on clicking on the form1_button, form2 opens. In Form2, I entered a text in form2_textbox & then clicked the button (form2_button).ON click event of this button, it will send the text to form1's textbox & form1 will come in focus with its empty form1_textbox with a text received from form2.
I am using properties to implement this task. FORM2.CS
public partial class Form2 : Form
{
//declare event in form 2
public event EventHandler SomeTextInSomeFormChanged;
public Form2()
{
InitializeComponent();
}
public string get_text_for_Form1
{
get { return form2_textBox1.Text; }
}
//On the button click event of form2, the text from form2 will be send to form1:
public void button1_Click(object sender, EventArgs e)
{
Form1 f1 = new Form1();
f1.set_text_in_Form1 = get_text_for_Form1;
//if subscribers exists
if(SomeTextInSomeFormChanged != null)
{
SomeTextInSomeFormChanged(this, null);
}
}
}
FORM1.CS
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public string set_text_in_Form1
{
set { form1_textBox1.Text = value; }
}
private void form1_button1_Click(object sender, EventArgs e)
{
Form2 f2 = new Form2();
f2.Show();
f2.SomeTextInSomeFormChanged +=new EventHandler(f2_SomeTextInSomeFormChanged);
}
//in form 1 subcribe to event
Form2 form2 = new Form2();
public void f2_SomeTextInSomeFormChanged(object sender, EventArgs e)
{
this.Focus();
}
}
In form2 you need to create event and subscribe to it in form1. Thats all.
//declare event in form 2
public event EventHandler SomeTextInSomeFormChanged;
// call event in form2 text_changed event
if(SomeTextInSomeFormChanged != null)
SomeTextInSomeFormChanged(this, null);
//in form 1 subcribe to event
var form2 = new Form2();
form2.SomeTextInSomeFormChanged += SomeHandlerInForm1WhereYouCanSetForcusInForm1
Update:
Form2:
public Form2()
{
InitializeComponent();
}
public void button1_Click(object sender, EventArgs e)
{
//if subscribers exists
if(SomeTextInSomeFormChanged != null)
{
SomeTextInSomeFormChanged(form2_textBox1, null);
}
}
Form1:
public partial class Form1 : Form {
public Form1() { InitializeComponent(); }
private void form1_button1_Click(object sender, EventArgs e)
{
Form2 f2 = new Form2();
f2.Show();
f2.SomeTextInSomeFormChanged +=new EventHandler(f2_SomeTextInSomeFormChanged);
}
public void f2_SomeTextInSomeFormChanged(object sender, EventArgs e)
{
var textBoxFromForm2 = (TextBox)sender;
form1_textBox1.Text = textBoxFromForm2.Text
this.Focus();
}
}
The website listed below has very good tutorials. This particular page demonstrates how this can be achieved:
http://www.vcskicks.com/data-between-forms.php
What about this.
((Form2)Application.OpenForms["Form2"]).textBox1.Text = "My Message";