views:

562

answers:

2

Hi to all.

I've a field in a database, this field has a maximum length, and I want to set a textbox to the appropriate width. I'm creating the textboxes in runtime. How can I calculate the value of width property?

For example, if I have a field nvarchar(5) named IDClient, and the font-Size is 13, I want to create a texbox with a width enough to write 5 chars.

+1  A: 

Specify

input type='text' size='5' width='w' ........>

You can calculate w=num_characters * k. Where k is constant. First keep k = 15. And then do hit and trial until u find the best fit.

Krishna Kant Sharma
Also you must keep in mind, that until font is a courier type. You must calculate k by width of 'w'. Because it is the widest alphabet.
Krishna Kant Sharma
Thanks!! Ok, lets supose that I find the perfect K value for size = 5. What happens when the font size changes? The problem is that I only know the font size in runtime. I need some algorithm that calc W using size and lenght of the string.
Jonathan
I know its not the best approach. But you can make it:w= num_chars * font_size * k;and then find k.Since width will be directly proportional to the font size (in linear fashion). THere will exist a valid value of k for a font face.
Krishna Kant Sharma
Ok, Thanks again! I will test it right now.
Jonathan
+2  A: 

Maybe should use TextRenderer.MeasureText(string, font).

Here a little sample which should might help you

        //Get this value from somewhere...
        TextBox textBox = new TextBox();
        int maxWidth = 10;
        int extraSpace = 3;

        //Create sample string
        StringBuilder sb = new StringBuilder(maxWidth);
        sb.Append('w', maxWidth);

        //Measure text 
        Size size = TextRenderer.MeasureText(sb.ToString(), textBox.Font);

        //Set width of TextBox to needed width
        textBox.Width = size.Width + extraSpace;
Oliver