How do you get the size of a string? In Windows Forms it\'s easy, I just use graphics object and then MeasureString function. In ASP.NET I\'m not sure how to do this.
Returns the length of the string (number of characters).
C#
string MyString = "Stack Overflow String";
Response.Write(MyString.Length);
VB.net
Dim MyString As String = "Stack Overflow String"
Response.Write(MyString.Length);
MSDN Reference
http://msdn.microsoft.com/en-us/library/system.string.length.aspx
I'm not sure why so many people are apparently determined to put forward the idea that it is 'flat out impossible' to do this server side, it isn't. You just need to be a little bit creative, and be willing to do a lot of testing.
There is no native function I know of to measure the pixel dimensions of a string. You can achieve it in the following ways. Note you need to know:
1. Render it to an image and measure image size
Draw the text to a bitmap, and then measure it. This should be reasonably exact.
2. Use a fixed width font
If you are using a fixed width font and the text doesn't wrap, you can simply multiply its width by the number of characters.
3. Rough estimation
You could get a reasonably rough estimation on non fixed width fonts by picking some arbitrary character width number and multiplying it by total characters. Depends how accurate you want to be.