Jul 9, 2007

With VB.NET, there is no TextWidth method of Object like we have in VB.

TextWidth : Returns the width of a text string as it would be printed in the current font of a Form, PictureBox, or Printer.


Syntax in VB


object.TextWidth(string)


The TextWidth method syntax has these parts:

object Optional. An object expression that evaluates to an object in the Applies To list. If object is omitted, the Form with the focus is assumed to be object.


String Required. A string expression that evaluates to a string for which the text width is determined. Parentheses must surround the string expression.



Remarks


The width is expressed in terms of the ScaleMode property setting or Scale method coordinate system in effect for object. Use TextWidth to determine the amount of horizontal space required to display the text. If string contains embedded carriage returns, TextWidth returns the width of the longest line.

So What do in VB.NET ?


Well there is a way. Suppose we need to acquire the width of text in a TextBox as TextBox1
Dim myGraphics As System.Drawing.Graphics
myGraphics = Me.CreateGraphics

MsgBox(myGraphics.MeasureString(TextBox1.Text, Me.Font).Width)


This Could be very helpful in MSFlex Grid

You need to Resize Column Width of MSFlexGrid depending upon the Maximum Text width

Private Sub SizeColumns()
Dim g As Graphics = Me.CreateGraphics()
Dim myGraphics As System.Drawing.Graphics
myGraphics = Me.CreateGraphics
Dim FlexWidth2Trans As Integer
FlexWidth2Trans = (1440 / g.DpiX)

NOTE: MSFlexGrid uses twips, but .NET uses pixels. So by multiplying the inches by 1440, the twips to pixel conversion now gives the same result as in the original

Dim row_num As Integer
Dim col_num As Integer
Dim max_width As Single

For col_num = 0 To AxMSFlexGrid1.Cols - 1
max_width = 0
For row_num = 0 To AxMSFlexGrid1.Rows - 1
If max_width < myGraphics.MeasureString(AxMSFlexGrid1.get_TextMatrix(row_num, col_num), Me.Font).Width Then max_width = myGraphics.MeasureString(AxMSFlexGrid1.get_TextMatrix(row_num, col_num), Me.Font).Width * FlexWidth2Trans End If Next row_num AxMSFlexGrid1.set_ColWidth(col_num, max_width + 240) Next col_num End Sub

No comments: