C# – multiline textbox auto adjust it’s height according to the amount of text

cwinforms

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.

Best Answer

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;
     }
} 
Related Topic