格式化 textbox.text 特定格式,如:##.###.###/####-##

Formatting textbox.text specific format like : ##.###.###/####-##

我需要 14 个字符的格式:

10.257.938/0001.45

但是当我执行这段代码时,我得到

.###.###/####-

在我的 txtcnpj.text.

我真的不喜欢用maskedbox。 这是我的代码(关于失去焦点。):

Private Sub txtcnpj_LostFocus(sender As Object, e As EventArgs) Handles txtcnpj.LostFocus

        If Len(txtcnpj.Text) > 0 Then

            Select Case Len(txtcnpj.Text)

                Case Is = 11
                    txtcnpj.Text = Format(txtcnpj.Text, "###.###.###-##")

                Case Is = 14
                    txtcnpj.Text = Format(txtcnpj.Text, "##.###.###/####-##")
                    
            End Select
        End If
    End Sub

OR WHEN I USED ##.###.###/####-## RETURN

由安德鲁莫顿解决, 泰·安德鲁。乌胡尔.

在我的案例中,解决方案是:

Private Sub txtcnpj_LostFocus(sender As Object, e As EventArgs) Handles txtcnpj.LostFocus

    If Len(txtcnpj.Text) > 0 Then

        Select Case Len(txtcnpj.Text)

                      Case Is = 14
                Dim A As String
                A = txtcnpj.Text.Replace("."c, "").Replace("/"c, "")
                txtcnpj.Text = String.Concat(A.Substring(0, 2), ".", A.Substring(2, 3), ".", A.Substring(5, 3), "/", A.Substring(8, 4), "-", A.Substring(12, 2))

        End Select
    End If

End Sub

这样的格式适用于数字,而不是字符串。

自己写方法最简单,例如:

Option Strict On

Module Module1

    Function FormatWithSlash(s As String) As String
        s = s.Replace("."c, "").Replace("/"c, "")
        Return String.Concat(s.Substring(0, 2), ".", s.Substring(2, 3), ".", s.Substring(5, 3), "/", s.Substring(8, 4), ".", s.Substring(12, 2))
    End Function

    Sub Main()
        Console.WriteLine(FormatWithSlash("12345678901234"))
        Console.WriteLine(FormatWithSlash("10.257.938/0001.45"))

        Console.ReadLine()

    End Sub

End Module

输出:

12.345.678/9012.34
10.257.938/0001.45