Adriano Santros
Adriano Santros

Reputation: 138

Setting Width of Textbox according to maxlenth

I am using winforms application and i want to set that width of textbox which will show characters till max length,in short something like width = maxlength.Any predefined property is there? or we have to calculate it manually?

//I am looking for this type of logic

  private void Form1_Load(object sender, EventArgs e)
    {
        //sample project
        textBox2.Width = textBox2.MaxLength;
        textBox3.Width = textBox3.MaxLength;
        textBox4.Width = textBox4.MaxLength;
    }

Upvotes: -1

Views: 2791

Answers (3)

TaW
TaW

Reputation: 54433

You have a Unit Mismatch: Width is in Pixels, MaxLength in characters.

So you need to measure the Font using e.g. Graphics.MeasureString.. Works best for fixed Fonts like Consolas.

You can measure the font e.g. like this, using 'x' as a medium width letter:

using (Graphics G = textBox2.CreateGraphics())
   textBox2.Width = (int) (textBox2.MaxLength * 
                           G.MeasureString("x", textBox2.Font).Width);

There are other Font measurement methods like TextRenderer.MeasureText you could use; also both methods have options to fine tune the measurement. The default above will include some leeway.

If you use a fixed Font the width will be OK, if you don't you'll need to decide whether you'd rather be on the safe side (use "W" or "M" to measure) or not. "X" is a likely compromise. Or you could adapt dynamically in the e.g. the TextChanged event..

Upvotes: 3

Vishal
Vishal

Reputation: 2017

Try this:

textbox1.MaxLength = 0//The default value is 0, which indicates no limit;

Refer this msdn link for more info:

msdn link for textbox maxlength

Upvotes: 1

user3967508
user3967508

Reputation:

Use the Anchor property to define how a control is automatically resized as its parent control is resized Anchoring a control to its parent control ensures that the anchored edges remain in the same position relative to the edges of the parent control when the parent control is resized.

Upvotes: 0

Related Questions