Programmatically Add a Control to a TabPage

MoonKnight picture MoonKnight · May 18, 2012 · Viewed 13.3k times · Source

All, I want to add a custom RichTextBox to a WinForm TabPage. I have tried various things illustrated by the code below

TabPage tmpTabPage = new TabPage("Test");
tabControl1.TabPages.Add(tmpTabPage);

CustomRichTextBox tmpRichTextBox = new CustomRichTextBox();
tmpRichTextBox.LoadFile(@"F:\aaData\IPACostData\R14TData\ACT0\1CALAEOSAudit_log.rtxt");

// Attempted FIX.
tabControl1.SuspendLayout();
tabControl1.TabPages["Test"].Controls.Add(tmpRichTextBox); // This throws a NullReferenceException??
tabControl1.ResumeLayout();

tmpRichTextBox.Parent = this.tabControl1.TabPages["test"];

tmpRichTextBox.WordWrap = tmpRichTextBox.DetectUrls = false;
tmpRichTextBox.Font = new Font("Consolas", 7.8f); 

tmpRichTextBox.Dock = DockStyle.Fill;
tmpRichTextBox.BringToFront();

Before I added the "aAttempted FIX", the code would run without exception but the CustomRichTextBox would not appear. Now I get the NullReferenceException and I am confused over both situations. What am I doing wrong here?

Answer

Samir picture Samir · May 18, 2012

What you're really missing is setting the "Name" property for your TabPage variable. The string you're passing to TabPage's constructor is only setting the TabPage.Text property.

Just add the following code after instantiating your TabPage and you should be fine:

TabPage tmpTabPage = new TabPage("Test");
tmpTabPage.Name = "Test"
// Rest of your code here

The reason you are getting the NullReferenceException is because the following code:

tabControl1.TabPages["Test"]

is not returning a reference to the TabPage, because the TabPage's "Name" property was not set.