I have a textbox which can return various strings ranging from 5 characters upto 1000 characters in length. It has the following properties:
Which other properties of the textbox do I need to set to make the following possible?
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;
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With