tags:

views:

2725

answers:

3

I have a string like this:

string s = "This is my string";

I am creating a telerik report and I need to define a textbox that is the width of my string. However the size property needs to be set to a Unit (Pixel, Point, Inch, etc). How can I convert my string length into, say a Pixel so I can set the width?

EDIT: I have tried getting a reference to the graphics object, but this is done in a class that inherits from Telerik.Reporting.Report.

+3  A: 

You can create an instance of a graphics object an use the MeasureString() method. But you will need to pass it the font name, font size, and other info.

Mitchel Sellers
I have font name, size, etc. I have looked at the MeasureString method, but cannot figure out how to create a Graphics object reference. I don't have a form or control, I am just trying to figure this out in a class.
Scott
+2  A: 

Depends on the font, too. String length isn't sufficient.

duffymo
+6  A: 

Without the use of a control or form.

        using (System.Drawing.Graphics graphics = System.Drawing.Graphics.FromImage(new Bitmap(1, 1)))
        {
            SizeF size = graphics.MeasureString("Hello there", new Font("Segoe UI", 11, FontStyle.Regular, GraphicsUnit.Point));
        }

Or in VB.Net

    Using graphics As System.Drawing.Graphics = System.Drawing.Graphics.FromImage(New Bitmap(1, 1))
        Dim size As SizeF = graphics.MeasureString("Hello there", New Font("Segoe UI", 11, FontStyle.Regular, GraphicsUnit.Point))
    End Using
Tom Anderson
Seems to me that MeasureString should have been a static method.
Kibbee