Search code examples
vb.netvb6

BC42322 VB.NET Runtime errors might occur when converting 'String' to 'IFormatProvider'


I'm trying to migrate old VB6(Visual Basic 6.0) Project to VB.net framework 4.6x. But I had to migrate it to .net framework 2.0 first.

I used to convert numbers in TextBox to formatted numbers using ToString as below. In Visual Studio 2017 .net framework 2.0, I have BC42322 warning. Is there a way to solve this?

txtDividend.Text = txtDividend.Text.ToString("###,###,##0")

I also have

On Error GoTo Error_Handle

at the start of the function to handle characters in that textbox


Solution

  • The Text property is already a string, and the ToString() method for string doesn't have the overload you want.

    Since it seems this same text field can hold both the formatted and unformatted version of a value, what you may want to do is first strip off any formatting, convert to a numeric type like Integer or Decimal, and then use the ToString() method from there:

    Public Function FormatDividend(dividend As String) As String
        Dim extraCharacters As New Regex("[^\d,.-]")
        dividend = extraCharacters.Replace(dividend, "")
        Return FormatDividend(CDec(dividend))
    End Function
    Public Function FormatDividend(dividend As Decimal) As String
        Return Dividend.ToString("###,###,##0")
    End Function
    

    You can call those functions like this:

    txtDividend.Text = FormatDividend(txtDividend.Text)
    

    And of course you can tweak that expression however you want, or change the overload and cast to use Integer instead of Decimal.