Kelvin TK

Kelvin TK

  • NA
  • 61
  • 5k

addcommas a number string in vb.net

Feb 7 2011 8:49 PM

Public Function addCommas(ByVal str As String, ByVal typeflag As Boolean) As String 
str = str.Trim
        If str = "" Then
            Return str
            Exit Function
        End If
        If Mid(str, 1, 1) = "$" And IsNumeric(Mid(str, 2, 1)) Then
            Return str
            Exit Function
        End If
        If IsNumeric(str) = False Then
            MessageBox.Show("Wrong Number !!")
            Return ""
            Exit Function
        Else
            'Dim m As Integer = 0
            'm = str.Length / 3
            'If m > 0 Then
            '    If InStr(m, str, ",") > 0 Then
            '        Return str
            '        Exit Function
            '    End If
            'End If
        End If
        Dim strcue As String
        strcue = ""
        Dim tflag As Boolean
        tflag = False
        tflag = typeflag
        ' MessageBox.Show(str.Length)
        'Dim o As Integer
        'o = 0
        'o = strlen - 2
        'Dim v As Integer = 0
        'v = str.Length - 2
        Dim n As Integer
        'm = 0 some variable not carried at for loop
        For n = (str.Length - 2) To 0 Step -3
            strcue = "," + Microsoft.VisualBasic.Strings.Mid(str, n, 3) + strcue
        Next

        If str.Length Mod 3 > 0 Then
            strcue = Mid(str, 1, str.Length Mod 3) & strcue
        Else
            strcue = Right(strcue, strcue.Length - 1)
        End If
        If tflag = True Then
            strcue = "$" & strcue
        End If
        Return strcue
 End Function
' The above module always has error in the bold region. System.ArgumentException is unhandled  Message="?? 'Start' ??????" / parameter 'start' must be greater than zero ~

And, I found that the n variable do not carry any value sometimes when the event is triggered

Answers (3)