title: C# - Creating controls dynamically and accessing them
body: <p>I'm creating a simple notepad type of application with the tab functionality. I'm creating the TabControl, its TabPages and RichTextBoxes at run-time. I have them instantiated at class scope. And there is a MenuStrip item called New, by clicking that you can add more tab pages.</p>
  
  <pre><code>TabControl tbcEditor = new TabControl();
  TabPage tbPage = new TabPage();
  RichTextBox rtb = new RichTextBox();
  
  private void frmTextEditor_Load(object sender, EventArgs e)
  {
       Controls.Add(tbcEditor);
       tbcEditor.Dock = DockStyle.Fill;
       tbcEditor.TabPages.Add(tbPage);
       tbPage.Controls.Add(rtb);
       rtb.Dock = DockStyle.Fill;
  }
  
  private void newToolStripMenuItem_Click(object sender, EventArgs e)
  {
       //TabPage tbPage = new TabPage();
       //RichTextBox rtb = new RichTextBox();
  
       tbPage.Controls.Add(rtb);
       rtb.Dock = DockStyle.Fill;
       tbcEditor.TabPages.Add(tbPage);
  }
  </code></pre>
  
  <p>The problem I'm facing is a bit difficult to explain. I'll try my best. When the form loads, everything works as expected. The TabControl creates with a TabPage with a RichTextBox added. However if I click that New button to add another page, it goes bonkers. A new TabPage gets created but without a RichTextBox added. No errors are thrown either. If I un-comment out those 2 lines(under MenuItem click event), which creates 2 instances of TabPage and RichTextBox, everything works as I want. </p>
  
  <p>Now my first question is why do I have to make new instances of only those 2 types(TabPage, RichTextBox) again but not TabControl? As you can see in the last line, I can use <code>tbcEditor</code> once again. But not <code>tbPage</code> and <code>rtb</code>.</p>
  
  <p>Sure I can go on declaring them again at local scope but another issue arises then. If I want to say, add copy, paste functionality, I should do something like this,right?</p>
  
  <pre><code>Clipboard.SetDataObject(rtb.SelectedText);
  </code></pre>
  
  <p>But I can't access <code>rtb</code> since it is declared as local. </p>
  
  <p>I'm very baffled by this so any suggestions, ideas on how to overcome these 2 issues would be greatly appreciated.</p>
  
  <p>Thank you.</p>