Search code examples
.netline-numbers

Get Visual Basic line number and use in messagebox


I am constantly chasing errors in my code and I place message boxes in stating "Line xyz value = " etc.

But when I change my code I am constantly having to push the numbers and can't find them when I am finished or miss one here and there.

Just out of curiosity, but when the error flags in the JIT debugger it can tell me the module and the line number. Does anyone know if I can obtain that so that as the line numbers change so will my messagebox?

This would be a fantastic help. The reason I ask is because I am programming in AutoCAD and have no ability to debug in real time.

Any help would be appreciated.


Solution

  • Use CallerLineNumberAttribute as an attribute on a parameter for a MsgBox wrapper.

    Public Shared Module MyFunctions
    
        Public Sub MsgBoxWithLineNumber( msg As String, <CallerFilePath> Optional  file As String = Nothing, <CallerLineNumber> Optional  lineNumber As Integer = 0)
            
            Dim msg2 As String = msg & vbCrLf & vbCrLf & file & vbCrLf & "Line " & lineNumber
            MessageBox.Show( msg2, "Error" )
            
        End Sub
    
    End Module
    

    For example:

    Public Sub Foobar()
    
        MsgBoxWithLineNumber( "foobar" )
        
    
    End Sub
    

    Will give you this Message box:

    ---------------------------
    Hi
    ---------------------------
    hello
    
    
    
    C:\Users\Me\AppData\Local\Temp\LINQPad6\_voxwvlsv\sonnkr\LINQPadQuery.vb
    
    Line 81
    ---------------------------
    OK   
    ---------------------------
    

    Screenshot proof (via Linqpad):

    enter image description here