Question Textbos dimensions vs. font size

cbreemer

Well-known member
Joined
Dec 1, 2021
Messages
188
Programming Experience
10+
In my new WinForms project I have a series of 1-digit textboxes, like this:

a.jpg


I would like the digits to fit more snugly in their boxes, with not so much whitespace around them. But I can't get the textbox any smaller, or the font any bigger.
The TextBoxes have zero margin and center text. The font used is Consolas 16pt. I would like to be able to set the
TextBox size to (20,20) for example, but the designer does not accept anything smaller than(20,32). Not even when I change it manually in Form1.Designer.cs.
I had the same issue with a label (the dot in the Gas reading), but setting the label's AutoSize propertry to false fixed that.
Alas, TextBox does not seem to have this property. Any ideas out there ?

The code :
Textbox definitions:
this.textBox1.Font = new System.Drawing.Font("Consolas", 15.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.textBox1.Location = new System.Drawing.Point(12, 358);
this.textBox1.Margin = new System.Windows.Forms.Padding(0);
this.textBox1.MaxLength = 1;
this.textBox1.Name = "textBox1";
this.textBox1.Size = new System.Drawing.Size(32, 32);
this.textBox1.TabIndex = 1;
this.textBox1.Text = "0";
this.textBox1.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
 

Attachments

  • a.jpg
    a.jpg
    12.4 KB · Views: 17
Personally, I would just make a custom control to render a number like that instead of having to deal with multiple textboxes.
 
The reason is that TextBox auto-adjust to the height of the given font. AutoSize exist but is hidden: TextBoxBase.AutoSize Property (System.Windows.Forms)
That helps, thanks ! I wonder why they made that property hidden in the designer 🤔
So now I can use a bigger font which is great. Unfortunately the vertical centering does not keep working well. 10pt still looks good enough but 20 pt is way below the center. So TextBox is still getting the better of me.... Ah well.
 
Personally, I would just make a custom control to render a number like that instead of having to deal with multiple textboxes.
Ah yes, that would have been smarter, never thought of that. If I get into any more issues with the textboxes, or it's too much hassle, I may well go that way. Thanks !
 
I wonder why they made that property hidden in the designer 🤔
I would assume because it would generally be considered poor design to have a TextBox resize as the text within it changed. It makes sense for a Label, which generally doesn't display any chrome, but not so much for a TextBox.
 

Latest posts

Back
Top Bottom