Hi experts,
When I dynamically create a TextBox, what I only known is the TextBox can only input a fixed number letters. Now, I want to set the width of thisTextBox, andshow all input letters wholly. But,as we know, different letter has different width.For example, the width of letter "W" is wider than "i". So, I want to know how to set the width of TextBox, and can show the input text wholly.
thanks,
Gavin |
| Gavin.Guo Thursday, July 17, 2008 11:48 AM |
There's a fundamental flaw in your approach. As you noted, you cannot predict what the user is going to enter. You should size the text box wide enough for "most typically" entered strings. The control smoothly handles entry of text that doesn't quite fit the box. Trying to autosize it is just distracting and makes for an ugly UI. Note that Chinese words are almost always much smaller, one character represents an entire word. German is very wordy. Leave about 30% room to accomodate non-English languages.
|
| nobugz Saturday, July 19, 2008 4:15 PM |
Get a Graphics instance and use MeasureString method to get the size of the string according to the text and the font.
Graphics g = Graphics.FromHwnd(this.Handle); // or this.textBox.Handle SizeF size = g.MeasureString("abc", this.Font); // or this.textBox.Font
hth, Lior.
|
| Lior Salem Thursday, July 17, 2008 12:56 PM |
I'd say just experiment. In the designer fill a box with however many W's you want, size it to just fit and write down the width. Do it for a few lengths and you should be able to determine a base width + a width per W. Then size it like: textBox.Width = baseWidth + lengthRequired * letterWidth;
|
| ScottyDoesKnow Thursday, July 17, 2008 5:16 PM |
Scotty, Thanks for your good suggestion. But I have a question: do you think letter 'W' is wide enough for all others? Just a thought, how about the other letters of different language? for example, chinese word is wider. I just don't want to add hard code in my code (just like letter "W"). Do you have other suggestion?
Lior, I know this method, but I want to get is setting dialog width according to the number of letter, (I don't know the string the user want to input)
thanks,
Gavin |
| Gavin.Guo Friday, July 18, 2008 3:27 AM |
There's a fundamental flaw in your approach. As you noted, you cannot predict what the user is going to enter. You should size the text box wide enough for "most typically" entered strings. The control smoothly handles entry of text that doesn't quite fit the box. Trying to autosize it is just distracting and makes for an ugly UI. Note that Chinese words are almost always much smaller, one character represents an entire word. German is very wordy. Leave about 30% room to accomodate non-English languages.
|
| nobugz Saturday, July 19, 2008 4:15 PM |
Thanks nobugz, I think it's the right way tosolve what I mentioned. |
| Gavin.Guo Monday, July 21, 2008 2:40 AM |