Visual Basic Tips

I provide these for reference only. Any code samples work as well as they work in my applications. Which means, they may be wrong and I haven't found any problems. Yet.


Table of Contents

  1. How do I check to see if an object is set to nothing?
  2. What about IsNullString()?
  3. And IsZeroLength()?
  4. Avoid IIF()
  5. PathCompactPath() Function; OBSOLETE; DO NOT USE

How do I check to see if an object is set to nothing?

How many will remember to use Is Nothing? I can't tell you how many times I forget this. So, I created a function to remember for me. I am pretty lazy, so I do things to make me more effective. I remember IsNull(), IsMissing()...So, I create functions for IsZeroLength(), IsNullString(), and...IsNothing(). Then I can avoid all the stupid logic constructs need to test variables.

The top version is my preference. It is easy to read, easy to debug, and easy for the compiler to optimize. I don't worry about the extra time for the function call. What slows Visual Basic down is string handling. Plain and simple.

Public Function IsNothing(ByRef objReference As Object) As Boolean
    If objReference Is Nothing Then
        IsNothing = True
    Else
        IsNothing = False
    End If
End Function
Public Function IsNothing(objReference as Object) as Boolean
    IsNothing = Not (objReference Is Nothing)
End Function

Or, if you prefer:

If obj Is Nothing Then
    Set obj = objSomething
End If
If Not (obj Is Nothing) Then
    Set obj = Nothing
End If

Also, notice I am a big believer in parentheses.

Back to Top

What about IsNullString()?

Once again, my preferred version is:

Public Function IsNullString(byval strValue as String) as Boolean
    If strValue = vbNullString Then
        IsNullString = True
    Else
        IsNullString = False
    End If
End Function

You could do:

IsNullString = Not (strValue = vbNullString)

Yeah right, I have money to make and coding to do. How would I debug that statement above easily? The answer is I could not. Leave the decoding to the intelligence experts.

Back to Top

And IsZeroLength()?

This works real well when working with record sets, and I do mean well:

If IsZeroLength(TextBox1) = False Then
    !Field1 = TextBox1
Else
    !Field1 = Null
End If

Or, if you prefer:

!Field1 = IIF(IsZeroLength(TextBox1), Null, TextBox1)
Back to Top

Avoid IIF()

IIF() is extremely slow. Better is If...Then...End If. You can even wrap If...Then...Else into a function, and it will still be faster than IIF():

Public Function My_IIF( _
    byref Expression as variant, _
    byref TruePart as Variant, _
    byref FalsePart as Variant) as Variant
'
    If Expression = True Then
        My_IIF= TruePart
    Else
        My_IIF= FalsePart
    End If
End Function

Hardcore Visual Basic has an excellent discussion the performance of IIF().

Back to Top

PathCompactPath() Function

Update - Use TextRenderer.MeasureText of .NET Framework version 2.0 to duplicate the functionality of PathCompactPath.

Truncates a file path to fit within a given pixel width by replacing path components with ellipses.

For displayed text, replaces characters in the middle of the string with ellipses so that the result fits in the specified rectangle. If the string contains backslash (\) characters, DT_PATH_ELLIPSIS preserves as much as possible of the text after the last backslash.

SS_PATHELLIPSIS

Ellipsis Path

C:\My Documents\Business\dBase\Assets\MISAssets2K5.mdb

C:\My Documents\Bu...\MISAssets2K5.mdb

Private Declare Function PathCompactPath Lib "shlwapi.dll" Alias "PathCompactPathA" ( _
    ByVal hdc As IntPtr, _
    ByVal lpszPath As System.Text.StringBuilder, _
    ByVal dx As Integer) As Integer

Private Sub Form_Load(ByVal eventSender As System.Object, ByVal eventArgs As System.EventArgs) Handles MyBase.Load
    '
    Const MAX_PATH As Integer = 260
    Dim oGraphics As Graphics = Label1.CreateGraphics
    Dim hDc As IntPtr = oGraphics.GetHdc
    Dim oPath As New System.Text.StringBuilder(g_sDataPath & "\" & g_sDataFile, MAX_PATH)
    
    PathCompactPath(hDc, oPath, Label1.Width)
    Label1.Text = oPath.ToString
    
    oGraphics.ReleaseHdc()
    oGraphics.Dispose()

    'if you do not release the device context then you will get
    '   An unhandled exception of type 'System.InvalidOperationException' occurred in system.drawing.dll
    '   The object is currently in use elsewhere.

End Sub

PathCompactPath, PathCompactPathEx, DrawText, DrawTextEx, DT_PATH_ELLIPSIS, DrawString, StringFormat, StringFormat.Trimming, StringFormat.Trimming.EllipsisPath, Ellipsis Path, Path Ellipsis, SS_PATHELLIPSIS

''' <summary>

''' Truncates a file path to fit within a given pixel width by replacing path components with ellipses.

''' </summary>

''' <param name="hdc">[in] A handle to the device context used for font metrics.</param>

''' <param name="lpszPath">[in, out] A pointer to a null-terminated string of length MAX_PATH that contains the path to be modified. On return, this buffer will contain the modified string.</param>

''' <param name="dx">[in] The width, in pixels, in which the string must fit.</param>

''' <returns>Returns TRUE if the path was successfully compacted to the specified width. Returns FALSE on failure, or if the base portion of the path would not fit the specified width.</returns>

''' <remarks>

''' <para>This Shell Lightweight Utility function uses the font currently selected in hDC to calculate the width of the text. This function will not compact the path beyond the base file name preceded by ellipses.</para>

''' <para>The .NET Framework version 2.0 contains the TextRenderer.MeasureText method, which can reproduce the functionality of the PathCompactPath function, as shown in the following example.</para>

''' <example>

''' <code>

'''    Public Function CompactPath(ByVal text As String, ByVal control As Control) As String

'''

'''        'make a copy because the measure text call is instructed to modify string

'''        Dim sResult As String = String.Copy(text)

'''

'''        TextRenderer.MeasureText(sResult, control.Font, control.ClientSize, TextFormatFlags.PathEllipsis Or TextFormatFlags.ModifyString)

''' 

'''        Return sResult

'''

'''    End Function

''' </code>

''' </example>

''' </remarks>

<Obsolete("In .NET 2.0, use TextRenderer.MeasureText with TextFormatFlags.PathEllipsis", True)> _

Declare Auto Function PathCompactPath Lib "shlwapi.dll" ( _

    ByVal hdc As IntPtr, _

    ByVal lpszPath As System.Text.StringBuilder, _

    ByVal dx As Int32) As Boolean

 

''' <summary>

''' Truncates a file path to fit within a given pixel width by replacing path components with ellipses.

''' </summary>

''' <returns>Returns the path compacted to the specified width. This function will not compact the path beyond the base file name preceded by ellipses. Therefore, the base portion of the path may not always fit within the specified width.</returns>

''' <remarks>

''' <para>Works well with monospace/fixed-width fonts. Tends to compact text too much when using proportional fonts.</para>

''' </remarks>

Public Function CompactPath(ByVal path As String, ByVal control As Control) As String

    Const MAX_PATH As Integer = 260

 

    Dim oPath As New System.Text.StringBuilder(path, MAX_PATH)

    Dim oGraphics As System.Drawing.Graphics = control.CreateGraphics

 

    Try

 

        If PathCompactPath(oGraphics.GetHdc, oPath, control.ClientSize.Width) Then

            'okay

        Else

            'failure or base name too long for specified width

        End If

 

    Finally

 

        If Not (oGraphics Is Nothing) Then

 

            'if you do not release the device context then you will get

            '   An unhandled exception of type 'System.InvalidOperationException' occurred in system.drawing.dll

            '   The object is currently in use elsewhere.

 

            oGraphics.ReleaseHdc()

            oGraphics.Dispose()

 

        End If

 

    End Try

 

    Return oPath.ToString

End Function

Back to Top
Created: 26 Oct 2001 01:39:57 -0700
Changed: 26 Feb 2009 18:41:08 -0800

Take Pride in America

envelope indicating e-mail address ton_y*missico.com