Programmatically Add a Control to a TabPage
Solution 1
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.
Solution 2
Try it like this by adding the tmpRichTextBox to tmpTabPage and then adding tmpTabPage to tabControl1
TabPage tmpTabPage = new TabPage("Test");
CustomRichTextBox tmpRichTextBox = new CustomRichTextBox();
tmpRichTextBox.LoadFile(@"F:\aaData\IPACostData\R14TData\ACT0\1CALAEOSAudit_log.rtxt");
// Attempted FIX.
tmpTabPage.SuspendLayout();
tmpTabPage.Controls.Add(tmpRichTextBox); // This throws a NullReferenceException??
tmpTabPage.ResumeLayout();
tmpRichTextBox.Parent = tmpTabPage;
tmpRichTextBox.WordWrap = tmpRichTextBox.DetectUrls = false;
tmpRichTextBox.Font = new Font("Consolas", 7.8f);
tmpRichTextBox.Dock = DockStyle.Fill;
tmpRichTextBox.BringToFront();
//tmpTabPage.Controls.Add(tmpRichTextBox);
tabControl1.TabPages.Add(tmpTabPage);
MoonKnight
Updated on June 04, 2022Comments
-
MoonKnight almost 2 years
All, I want to add a custom
RichTextBox
to a WinFormTabPage
. I have tried various things illustrated by the code belowTabPage 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 theNullReferenceException
and I am confused over both situations. What am I doing wrong here?