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.
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);
}
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.
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 tbcEditor once again. But not tbPage and rtb.
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?
Clipboard.SetDataObject(rtb.SelectedText);
But I can't access rtb since it is declared as local.
I'm very baffled by this so any suggestions, ideas on how to overcome these 2 issues would be greatly appreciated.
Thank you.