I have a Windows Forms Application with a global variable - a string called testPath
.
This string is used to save a path - by default it is C:\temp\
. When the user clicks a button, this directory is created (if it does not exist already).
There is also a textbox control, in case the user wants to change the value of the path.
At the button's event handler, I try to access testPath
and I get a null reference.
I am not changing the value of testPath
anywhere, except when I pass it to and from the textbox Control.
What am I doing wrong? How does the global variable have something inside at one second, and then right afterwards it points to a null reference?
Here is the complete code:
public string testPath = @"C:\temp\";
public MainForm()
{
//Windows Designer call
InitializeComponent();
//Show the testPath in the textBox (using Invokes)
this.textBox1.Invoke(new MethodInvoker(delegate { this.textBox1.Text = testPath; } ));
//here, testPath contains 'C:\temp\'
}
//Button "Click" handler
private void Button1Click(object sender, EventArgs e)
{
//here, testPath contains a null reference!
//If the user changed testPath in the textBox, we need to save it again
this.textBox1.Invoke(new MethodInvoker(delegate { testPath = this.textBox1.Text; } ));
//Create the path
if(!Directory.Exists(testPath)) //If it does not exist already
{
Directory.CreateDirectory(testPath);
}
//...Do something else
}