Note that there are some explanatory texts on larger screens.

plurals
  1. POC# - Can't access a global variable from an event handler
    text
    copied!<p>I have a Windows Forms Application with a global variable - a string called <code>testPath</code>.</p> <p>This string is used to save a path - by default it is <code>C:\temp\</code>. When the user clicks a button, this directory is created (if it does not exist already).</p> <p>There is also a textbox control, in case the user wants to change the value of the path.</p> <p>At the button's event handler, I try to access <code>testPath</code> and I get a null reference.</p> <p>I am not changing the value of <code>testPath</code> anywhere, except when I pass it to and from the textbox Control.</p> <p>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?</p> <p>Here is the complete code:</p> <pre><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 } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload