Are you sure- it the desired output you want to have? Because, itmay resize and relocatte your controls on the screen according to the changed height of the RichTextBox.
However- if you wish to do so..... :)
There would be some complex solutions to this.
But, I would give you a smart and robust solution.
Let me first define your problem in a simple way for better understanding:
You have a richTextBox of fixed Width. You want to vary the Height of RichTextBox depending on the length of Text. Right?
So, now on the same understanding, please find this method to resize you RichTextBox's height depending on text.
/// <summary>
/// Purpose: To adjust the height of a RichTextbox depending on the length of Text
/// Logic: Use a Label-control for reference.
/// Fix Label's MinumumSize, same as the width and height of the RichTextbox.
/// Fix Label's MaximumSize(Width), same as the width of the RichTextbox so that width does not increase.
/// Assign Label's MaximumSize(Height), to be far greater than the Height of RichTextbox.
/// Set Label's Text, same as Textbox's Text .
/// Now, the Label would resize itself because of AutoSize.
/// So, set the height of RichTextbox same as of Label's.
/// </summary>
/// <param name="richTextBox1">RichTextbox whose height is to be adjusted.</param>
private void ResizeRichTextBox(RichTextBox richTextBox1)
{
try
{
Label lblPrototype = new Label();
lblPrototype.AutoSize = true;
lblPrototype.Font = richTextBox1.Font;
lblPrototype.BorderStyle = BorderStyle.FixedSingle;
lblPrototype.MinimumSize = new Size(richTextBox1.Width, richTextBox1.Height);
lblPrototype.MaximumSize = new Size(richTextBox1.Width, richTextBox1.Height * 10);
lblPrototype.AutoSize = true;
lblPrototype.Text = richTextBox1.Text;
richTextBox1.Height = lblPrototype.PreferredHeight;
}
catch (Exception ex)
{
ex = new Exception("Error occurred while deciding vertical scroll for Textbox. " + ex.Message);
throw ex;
}
}
Now, please do change the location of textBox and other controls below this RichTextBox.
As the height increases, it would cover the below controls.
You may need to calculate the correct Location from initial location and the height of the richTextBox now.
Or, you can think of some way to update the location of textBox etc below the richTextBox.
Or, you can dock the richTextBox and TextBox in a Panel.
Regards,
Lakra :)
- If the post is helpful or answers your question, please mark it as such.