简体   繁体   中英

RichTextBox text is not shown C#

using richtextbox control programatically i'm appending text to the richtextbox .

richTextBox1.AppendText("hello");

somehow the text appears in the richTextBox1.Text but is not shown in the form. any idea of what might be the problem? (I checked the forecolor seems ok). Thanks in advance

Edit: found the root cause (had by mistake the initializeComponent() twice. )

private void InitializeComponent()
{
    this.richTextBox1 = new System.Windows.Forms.RichTextBox();
    this.SuspendLayout();
    // 
    // richTextBox1
    // 
    this.richTextBox1.Location = new System.Drawing.Point(114, 104);
    this.richTextBox1.Name = "richTextBox1";
    this.richTextBox1.Size = new System.Drawing.Size(100, 96);
    this.richTextBox1.TabIndex = 0;
    this.richTextBox1.Text = "";
    // 
    // Form1
    // 
    this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
    this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
    this.ClientSize = new System.Drawing.Size(284, 262);
    this.Controls.Add(this.richTextBox1);
    this.Name = "Form1";
    this.Text = "Form1";
    this.Load += new System.EventHandler(this.Form1_Load);
    this.ResumeLayout(false);

}

   public Form1()
    {
            InitializeComponent();
            InitializeComponent();

    }

    private void Form1_Load(object sender, EventArgs e)
    {
        richTextBox1.AppendText("hello world");
    }`

but still curious about why did this cause this weird behavior?

Does the same happen when you do richTextBox1.Text = "hello"; ?

EDIT: trying to explain the problem

Without seeing the entire code it's difficult for me to know for sure.

But my guess is, that something caused your OnLoad event handler to be called from within the first call to InitializeComponent , and then in the second call the RichTextBox was replaced with a new instance, and your text was added to the old instance.

If you post the minimal code that still has behavior (including the content of InitializeComponent ), I can try help figure out the reason.

EDIT 2

Well, when you call InitializeComponent twice, you actually create two instances of all the controls on your Form . So what happened was, the first call created one RichTextBox . Then the second call created another RichTextBox in exactly the same location, with the same size. Then you set the text to the second RichTextBox .

The reason you can't see the text is because the first RichTextBox is hiding the second one! To test that, you can add some code to change the location of richTextBox1 after you set its text, and then you'll see that there are two of them...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM