Related
I am trying to set a ConstantLine for a DevExpress SplineChart that is created in the Form1 from Form2 and also set a numericalupdown.value placed in the Form2 for a textBox.text that is placed in the Form1, whilst both Form1 and Form2 are Open and running.
I am using from accessors {get;set;} to get and set values of DevExpressChart as i have written down in my codes.
I can get the values, but i can't set any value without using Form1.ShowDialog().
I have also used Form1.Update(); andForm1.Refresh(); but the mentioned code only run successfully with the use of Form1.Show(); or Form1.ShowDialog();
However, i want them to execute while both forms are running Form2 as a child of Form1 an seeing the changes in the Form1
Code
//Code Snippet in the Form2:
//NumericalUpDown-ValueChanged Event: In Form2
private void numUpDnShkgTimeRstcConfig_ValueChanged(object sender, EventArgs e)
{
Form1 frm1 = new Form1();
if (chkBxShakingTimeRestCteLineConfig.Checked == true)
{
XYDiagram diagram = (XYDiagram)Frm1.SplineChart.Diagram;
diagram.AxisX.ConstantLines.Add(new ConstantLine("Shaking Time", Convert.ToString(numUpDnShkgTimeRstcConfig.Value)));
Frm1.TxtBx = Convert.ToString(numUpDnShkgTimeRstcConfig.Value);
}
}
//Code Snippet in the Form1
//Pass Objects And Parameter.
public DevExpress.XtraCharts.ChartControl SplineChart
{
get {return SplineChrt1Form1; }
set { SplineChrt1MainFrm = value; }
}
public string TxtBx
{
get { return txtBxSmplWt1Form1.Text; }
set { txtBxSmplWt1Form1.Text = value; }
}
...
The way I understood your problem was that:
You are displaying a Chart in Form1.
From Form1, you want to show a second form (Form2) that allows you to change or specify values for the Chart in Form1.
You want to get the updated values from Form2 in to Form1.
The best way to setup this sort of notification and updating of a parent form from a child form is to use Events. Events enable a child form to notify its parent without actually knowing anything about the parent.
Step 1 - Create an EventArgs class. This class will be used to hold the information you want to pass from Form2 to Form1.
Generally speaking, I find it is better to have the properties as Read Only and only set them in the constructor for this sort of event.
// I wasn't sure what the parameters were called or their type,
// so I just used an int and string to demonstrate the functionality
public class ChartValuesChangedEventArgs : EventArgs
{
public ChartValuesChangedEventArgs (int value1, string value2)
{
Value1 = value1;
Value2 = value2;
}
public int Value1 { get; private set; }
public string Value2 { get; private set; }
}
Step 2 - Declare the event that will be raised from Form2. This is what will notify the Parent (Form1) that the values have changed and what the values are.
public event EventHandler<ChartValuesChangedEventArgs> ValuesChanged;
Step 3 - Raise the Event. This is where you notify the Parent that the values have changed.
For this example, I am raising the event on a Button Click. You can just as easily put the content of this function in your own numUpDnShkgTimeRstcConfig_ValueChanged function.
private void button1_Click(object sender, EventArgs e)
{
ChartValuesChangedEventArgs chartValuesChangedEventArgs = new
ChartValuesChangedEventArgs(numUpDnShkgTimeRstcConfig.Value,
txtBxSmplWt1Form1.Text);
OnValuesChanged(chartValuesChangedEventArgs);
}
protected virtual void OnValuesChanged(ChartValuesChangedEventArgs e)
{
EventHandler<ChartValuesChangedEventArgs> handler = ValuesChanged;
if (handler != null)
{
handler(this, e);
}
}
Step 4 - Handle the event. This is where you update your chart with the new/updated values from Form2
private void ShowForm2Button_Click(object sender, EventArgs e)
{
Form2 form2 = new Form2();
form2.ValuesChanged += form2_ValuesChanged;
form2.Show();
}
void form2_ValuesChanged(object sender, ChartValuesChangedEventArgs e)
{
// Update the chart values here
Debug.Print(e.Value1.ToString());
Debug.Print(e.Value2);
}
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.
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.
I am working on a game that utilizes Windows Forms in C#. I want to be able to use the first form to call a second form. I have this working. Then I would like for the second form to send data back to the first form rather than creating a new instance of the first form. Can this be done? I know I need to have my properties set up so that I can set the variables from one form to the other. I am just not sure how to go about calling the first form without creating a new instance of it.
Is there a way that this can be done?
For example if I have Form A create an instance of Form B, can I have Form B do some work and send the data back to the original Form A without creating a new instance of Form A?
If you don't use the Data sent back Form A right away then you could use the Form_Closing event handler Form B and then a public property in Form B also.
In your Form A it could look like this:
public partial class FormA : Form
{
FormB frmB = new FormB(); // Instantiate FormB so that you could create an event handler in the constructor
public FormA()
{
InitializeComponent();
// Event Handler for Form Closing
frmB.FormClosing += new FormClosingEventHandler(frmB_FormClosing);
}
void frmB_FormClosing(object sender, FormClosingEventArgs e)
{
String fromFormB = frm2.FormBData; // Get Data from Form B when form is about to close
}
private void button1_Click(object sender, EventArgs e)
{
frmB.ShowDialog(); // Showing Form B
}
}
And in your Form B it could look like this:
private void button1_Click(object sender, EventArgs e)
{
// Let just say that the data is sent back once you click a button
FormBData = "Hello World!";
Close();
}
public String FormBData { get; set; }
It's hard to say without knowing your full requirements. But generally I go like this (Somewhat psuedo code).
Form2 dialogForm = new Form2();
if(dialogForm.ShowDialog() == DialogResult.OK)
{
this.PropertyOnForm1 = dialogForm.PropertyOnForm2
}
This ofcourse relies that your second form is a dialog. You will need to set the dialogresult buttons on Form2, and have a public property that will be accessed from Form1 once the dialog has been completed.
Let me know if this doesn't work and I'll write up a different answer.
Since you are creating Form2 in Form1, you can create a custom event in Form2 and subscribe to it in Form1 at the time that you create Form2, if you are returning information from Form2 when you are closing it then Edper's or MindingData's answers will work.
Here is a quick and dirty example using EventHandler<TEventArgs>
Form1
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Form2 frm2 = new Form2();
frm2.myCustomEvent += frm2_myCustomEvent;
frm2.Show();
}
void frm2_myCustomEvent(object sender, string e)
{
this.Text = e;
}
}
Form2
public partial class Form2 : Form
{
public event EventHandler<string> myCustomEvent;
int count;
public Form2()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
count +=1;
myCustomEvent(sender, count.ToString());
}
}
I have a MainForm and AnotherForm. AnotherForm is accessed via MainForm's menuItem.
AnotherForm has listView. When user clicks on an item it I want to get the string element and pass it to MainForm's textbox, so the element shows there and AnotherForm is closed. So far AnotherForm closes but nothing shows in the textbox in MainForm. Any suggestions?
private void listView1_ItemActivate(object sender, EventArgs e)
{
string input = listView1.SelectedItem[0].ToString();
MainForm mainF = new MainForm(input);// called the constructor
this.Close(); //close this form and pass the input to MainForm
mainF.inputTextBox.Text = input;
mainF.loadThis(input);
}
I assume you have an instance of MainForm already, and that's what creates an instance of AnotherForm.
Inside the event you posted, you're actually creating an entirely new instance of MainForm, never showing it, and then it's destroyed anyway when AnotherForm closes.
The reason you see nothing in the text box is because you're looking at the original instance of MainForm, which you haven't actually changed.
One quickie way of fixing this would be passing a reference to the original MainForm into AnotherForm:
public class AnotherForm
{
private MainForm mainF;
public AnotherForm(MainForm mainF)
{
this.mainF = mainF;
}
...
...
private void listView1_ItemActivate(object sender, EventArgs e)
{
...
mainF.inputTextBox.Text = input;
...
}
}
Note: Instead of having AnotherForm aware of MainForm, you might want to switch it around and create a public property in AnotherForm like this:
public class AnotherForm
{
public InputValue { get; private set; }
private void listView1_ItemActivate(object sender, EventArgs e)
{
...
InputValue = input;
...
}
}
Which you can then access from MainForm when the other form is closed:
private void SomeMethodInMainForm()
{
var newAnotherForm = new AnotherForm();
newAnotherForm.ShowDialog();
var inputValueFromAnotherForm = newAnotherForm.InputValue;
// do something with the input value from "AnotherForm"
}
If your MainForm has already been created you cannot just create another one in order to access it and set properties. You've created two separate MainForms (though the 2nd one is hidden because you never showed it).
It sounds like what you want to do is a modal dialog pattern. Your MainForm is the main window in your application. You want to have a 2nd form pop up when you click on a menu link. This is called a dialog. Then when you close that dialog you want your MainForm to retrieve a value as a returned result of the dialog.
In your MainForm the event handler which handles the menu item click should look something like this:
private void pickSomethingMenuItem_Click(object sender, EventArgs e)
{
using (var picker = new PickerDialog())
{
if (picker.ShowDialog(this) == DialogResult.OK)
{
LoadSomething(picker.SomethingPicked);
}
}
}
Then the following code would be inside your dialog form:
public string SomethingPicked { get; private set; }
private void somethingListView_ItemActivate(object sender, EventArgs e)
{
SomethingPicked = somethingListView.SelectedItem[0].ToString();
DialogResult = DialogResult.OK;
}
Notice how I named all of the objects with meaningful names. Well, except for "Something". It was impossible to tell from your code what you were actually using the dialog to pick. You should always use meaningful names for your objects and variables. Your code is almost completely nonsensical.
And you should almost never make a control on a Form public like you have with your inputTextBox. You should always expose values you want to share as public properties.
On this presented solution, you could do five main things in order to achieve what you want to do, namely:
1) Declare a global object for AnotherForm in MainForm
2) Initiate a FromClosing event handler for AnotherForm in MainForm
3) Make a public property or field in AnotherForm
4) Before closing in AnotherForm you save it the public property mentioned above
5) In the MainForm get the public property from AnotherForm
Here is the code:
MainForm
public partial class MainForm : Form
{
AnotherForm anotherForm; // Declare a global object for AnotherForm
public MainForm()
{
InitializeComponent();
}
private void showToolStripMenuItem_Click(object sender, EventArgs e)
{
anotherForm = new AnotherForm(); // when Menu Item is clicked instantiate the Form
anotherForm.FormClosing += new FormClosingEventHandler(anotherForm_FormClosing); // Add a FormClosing event Handler
anotherForm.ShowDialog();
}
void anotherForm_FormClosing(object sender, FormClosingEventArgs e)
{
inputTextBox.Text = anotherForm.listViewValue; // get the Value from public property in AnotherForm
}
}
AnotherForm
void listView1_ItemActivate(object sender, EventArgs e)
{
listViewValue = listView1.SelectedItems[0].Text; // Get the listViewItem value and save to public property
this.Close(); // Close
}
public String listViewValue { get; set; } // public property to store the ListView value
One thing to note here in comparison to your code I didn't use ToString() in ListView.SelectedItems:
listView1.SelectedItems[0].ToString();
But instead use the Text Property:
listView1.SelectedItems[0].Text;