RichTextBox text not showing C #

using richtextbox control programmatically i add text to richtextbox.

richTextBox1.AppendText("hello"); 

somehow the text appears in richTextBox1.Text , but does not appear on the form. any idea what might be the problem? (I checked that forecolor looks fine). thanks in advance

Edit: found the root cause (mistakenly used 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 wondering why this caused this weird behavior?

+4
source share
1 answer

The same thing happens when you execute richTextBox1.Text = "hello"; ?

EDIT: attempt to explain the problem

Not seeing all the code, it's hard for me to know for sure.

But I suppose something made the OnLoad event handler OnLoad called from 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 minimal code that still has behavior (including the contents of InitializeComponent ), I can try to figure out the reason.

EDIT 2

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

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

+5
source

Source: https://habr.com/ru/post/1333369/


All Articles