I have following problem:
I have a Form1
where I open a second Form2
from it. Now I have a save Button
in Form2
where entries from Textboxes are saved to a csv file. But I want to save some entries from Form1
too. The Textbox
entries from Form2
are getting saved but entries from Form1
are empty strings. Following code:
In Form1:
public void showInputToolStripMenuItem_Click(object sender, EventArgs e)
{
Form2 form2 = new Form2(this);
form2.Show();
}
to open the second Form via the first one and functions to grab the entries from the Form1 Textboxes:
public String getLocation()
{
return LocationBox.Text;
}
public String getFilesLoc()
{
return FilesLocation.Text;
}
In Form2 I have the following:
private Form1 m_form = null;
public Form2(Form1 f)
{
InitializeComponent();
m_form = f;
}
and then the function to grab the entries and save them:
private void button1_Click(object sender, EventArgs e)
{
Form1 form1 = new Form1();
proc.setParams(form1.getLocation(),getFilesLoc());
proc.saveCurrentSettings();
}
I left the other parameters out. So entries from Form2
are read correctly but the ones from Form1
are just an empty string (""). What can I do?
In the click handler, you're creating a new Form1
here:
Form1 form1 = new Form1();
That will have empty values - but you want the value from the existing form which you kept a reference to in your constructor - so use it!
private void button1_Click(object sender, EventArgs e)
{
proc.setParams(m_form.getLocation(), m_form.getFilesLoc());
proc.saveCurrentSettings();
}
(I'd strongly advise you to start following .NET naming conventions, quite possibly turning those get
methods into properties, and also considering passing the values into your Form2
constructor instead of the Form1
reference itself. It depends on whether you need to "see" any changes made to Form1
after the construction of Form2
.)
See more on this question at Stackoverflow