Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>A variable declared in a function is only visible in a function. You need to store the TextBoxes in a variable, that exists even when the code in the function has "finished". For more information search for <a href="http://msdn.microsoft.com/en-us/library/aa691132%28v=vs.71%29.aspx" rel="nofollow">scopes</a>.</p> <p>Here is a small sample that stores TextBoxes in a List that is visible in your class.</p> <p>Another option would be to use eventhandlers. It depends on your scenario, which solution would be suited better. If you store the TextBoxes in a List, you can easily perform clean up code (for instance remove EventHandlers if required). You can obviously combine Approach 1 and 2. In that case you would store the created TextBox in a List (or any other collection), but you would still use the <code>sender</code> in the eventhandler to get a reference to the sending TextBox.</p> <pre><code>public partial class Form1 : Form { List&lt;TextBox&gt; textBoxes = new List&lt;TextBox&gt;(); public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { //Approach 1: create and add textbox to list TextBox createdTextbox = new TextBox(); textBoxes.Add(createdTextbox); } private void button2_Click(object sender, EventArgs e) { //use the textboxes from the list foreach(TextBox t in textBoxes) { //do something with t } } private void button3_Click(object sender, EventArgs e) { //Approach 2: use eventhandlers and don't store textbox in a list TextBox createdTextbox = new TextBox(); createdTextbox.TextChanged += createdTextbox_TextChanged; listBox1.Items.Add(createdTextbox); } void createdTextbox_TextChanged(object sender, EventArgs e) { TextBox t = sender as TextBox; if (t == null) throw new ArgumentException("sender not of type TextBox", "sender"); //do something with t } } </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
 

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