Programmatically Add a Control to a TabPage

2019-02-26 01:26发布

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?

2条回答
迷人小祖宗
2楼-- · 2019-02-26 02:11

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); 
查看更多
贼婆χ
3楼-- · 2019-02-26 02:30

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.

查看更多
登录 后发表回答