You can't use label1
in a different forms because it's a private field of the form so you can't share value through this field. Also Label
is a visual component and not intended for data storage.
To share the value between the two forms, you can create a property in the second form that takes the value from first form. You can set the property in the first form after Excel file has been selected.
public class SecondForm : Form
{
private string _filePath;
public string FilePath
{
get { return _filePath; }
set { _filePath = value; }
}
...
}
When you creating a new form you can set the value from label1
or other place. For example if you open the second form immediately after choosing file you can use next code:
private void rectangleButton3_Click(object sender, EventArgs e)
{
using (OpenFileDialog ofd = new OpenFileDialog())
{
ofd.Filter = "Excel Files only | *.xlsx; *.xls; *.csv;";
ofd.Title = "Choose the file";
if (ofd.ShowDialog() == DialogResult.OK)
{
SecondForm secondForm = new SecondForm();
secondForm.FilePath = ofd.FileName;
secondForm.Show();
}
}
}
Finally you can read FilePath
in the second form because it's a part of your form and the value is already written from the first form.
If you need to access the value between many forms there are two ways to solve it.
"Good" and architecturally correct solution is to pass this value from form to form and to have a property for file path in each form. It's a right way because you will continue to have a loosely coupled architecture and be able to easily modify the code. For example the middle form may start to get the file path in a different way or the composition of the forms itself may change.
"Bad" and hacky solution is a global state with static
properties which you can read and write in any place:
public static class ApplicationState
{
private static string _filePath;
public static string FilePath
{
get { return _filePath; }
set { _filePath = value; }
}
}
So you can write ApplicationState.FilePath = ofd.FileName
or var filePath = ApplicationState.FilePath;
in any place of your code. But the problem is that this violates the encapsulation principle, making it difficult to test and modify the code when developing the project because you will have a single value within the entire application.