The Text
property gets reseted upon InitializeComponent
of the Form.
When you have a look at the Designer.cs
file of the Form
you should find a line like the following:
private void InitializeComponent()
{
this.richTextBoxEx1 = new WindowsFormsApp1.RichTextBoxEx(); //<-- RichTextBoxEx gets initialized and ITS constructor and InitializeComponent gets called
this.SuspendLayout();
//
// richTextBoxEx1
//
this.richTextBoxEx1.Location = new System.Drawing.Point(322, 106);
this.richTextBoxEx1.Name = "richTextBoxEx1";
this.richTextBoxEx1.Size = new System.Drawing.Size(100, 96);
this.richTextBoxEx1.TabIndex = 0;
this.richTextBoxEx1.Text = ""; //<-- Text Property gets reseted
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(800, 450);
this.Controls.Add(this.richTextBoxEx1);
this.Name = "Form1";
this.Text = "Form1";
this.ResumeLayout(false);
}
You can overcome this by overriding the OnCreateControl
So change your control to this:
public class RichTextBoxEx : RichTextBox
{
protected override void OnCreateControl()
{
Text = "Hello World";
base.OnCreateControl();
}
}
If the OnCreateControl
gets called multiple times - altough the definition of it on MSDN states:
The OnCreateControl method is called when the control is first created
Then you could force it to be called once by using a boolean to track if it got called or not, so try the following:
public class RichTextBoxEx : RichTextBox
{
private bool _initialized = false;
protected override void OnCreateControl()
{
if (!_initialized)
{
_initialized = true;
Text = "Hello World";
}
base.OnCreateControl();
}
}