Resizing a WinForms textbox control based on MaxLength

netresizetextboxwinforms

I've got a situation (a key-based search) where I'm going to have multiple inputs of varying, but constrained, length. So I'm building a common control to use for each input, and this control has a TextBox for use when the input type is free-form text. In that case I'd like the length of the TextBox to reflect the constraint placed on the input based on the TextBox's MaxLength property (or at least on a maximum length of some sort).

How can I do this? I realize this is technically impossible with variable width characters, but I'm interested in getting close. The fields vary in maximum length from 3 characters to around 90.

Best Answer

I would try to avoid this dynamic approach.
Do you really think that it adds value for the user? In my opinion it looks strange, when a common control has a different look all the time. Do you think the user can differ between a textbox that allows 32 characters and one that allows 29 characters? How about extrem values? When e.g. only three characters are allowed - or even 1024.
I'd make the TextBox the same length, always - that is better for your control and easier to implement. When the user needs a hint about the max lenght of the text add a label that says "29 characters left" and that updates during the input ...