Calculating width of TextBox dynamically based on Text in C#
Sometimes we need to expand the TextBox dynamically based on the length of the entered text. TextBox does not have a AutoSize property by which it can adjust it’s size based on the content. On way of calculating the Width for the TextBox is using the Graphics.MeasureString and calculating the Pixel width. This method has it’s Pros and cons.
A quick and easy (cheeky!!) method to do the same thing is to assign the text to a Label control’s Text property. With AutoResize of the label set to true, the Label’s width will automatically widen to fit the Text. Then use the Label’s width to set the width for the TextBox.
Label lbl = new Label(); lbl.AutoSize = true; lbl.Text = yourtextbox.Text; yourTextbox.Width = lbl.Width;
Have fun.
June 30th, 2009 at 8:02 am
Thanks a lot, that works very nicely.
Regards,
Ragini