Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

multiline textbox auto adjust it's height according to the amount of text

Tags:

c#

winforms

I have a textbox which can return various strings ranging from 5 characters upto 1000 characters in length. It has the following properties:

  • multiline = true
  • wordwrap = true

Which other properties of the textbox do I need to set to make the following possible?

  • The width of the box should be fixed
  • The height of the box to auto adjust depending on how much text it is returning e.g if the text runs onto 3 lines then it adjusts to 3 lines in height.
like image 384
whytheq Avatar asked May 13 '12 20:05

whytheq


2 Answers

Try this following code:

public partial class Form1 : Form
{
     private const int EM_GETLINECOUNT = 0xba;
     [DllImport("user32", EntryPoint = "SendMessageA", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]
     private static extern int SendMessage(int hwnd, int wMsg, int wParam, int lParam);


     public Form1()
     {
        InitializeComponent();
     }

     private void textBox1_TextChanged(object sender, EventArgs e)
     {
        var numberOfLines = SendMessage(textBox1.Handle.ToInt32(), EM_GETLINECOUNT, 0, 0);
        this.textBox1.Height = (textBox1.Font.Height + 2) * numberOfLines;
     }
} 
like image 177
Community Driven Business Avatar answered Sep 21 '22 00:09

Community Driven Business


There doesn't seem to be any functionality to do this built in to the TextBox class, but the Font class has a Height property that returns the number of pixels between baselines.

It is also possible to find out how many lines the text in the TextBox occupies, as described in this blog post (warning: it's not exactly elegant).

Once you've obtained this information, you should be able to make the TextChanged handler set the height of the TextBox accordingly using some simple maths.

like image 43
Harry Cutts Avatar answered Sep 22 '22 00:09

Harry Cutts