我怎样才能在文本框中输入首字母和其余数字的支票

时间:2019-04-04 14:22:36

标签: vb.net

我有一个vb.net代码,其中ID文本框正在检查订单ID是否仅为数字。现在我的老板要我用第一个字母和其他数字(如(A0000000))来更改此设置,因此他需要全数字,第一个字母和数字两种方式。 我现有的代码是。

    ElseIf (Not IsNumeric(txtworkorderID.Text)) Then
  invalidWorkOrderNumber = True

我该如何更改以检查是否全部为数字或字母数字? 我几乎没有编程知识。有人可以帮我吗?

2 个答案:

答案 0 :(得分:1)

您可以使用类似的功能吗?抱歉,您无法完全理解自己想要的东西。

 Function CheckForAlphaCharacters(ByVal StringToCheck As String)

                If Not Char.IsLetter(StringToCheck.Chars(0)) Then
                    Return False 'first character is not a letter
                End If

'other check if number
       For i = 1 To StringToCheck.Length - 1
                If Char.IsLetter(StringToCheck.Chars(0)) Then
                    Return False 'characters contain a letter
                End If
        next

            Return True 'Return true if first character is a letter and rest number
        End Function

基本上,它将检查字符串以查看第一个字符是否为字母,如果未返回false,则将检查第一个字符之后的每个字符以确保其不是字母。

If Regex.IsMatch(number, "^[0-9 ]+$") Then

'This will see if the whole string is all numbers! so maybe mix both this and the on above to confirm either ways acceptable?

End If

答案 1 :(得分:0)

您可以使用String.Substring进行此操作,以拉出每个零件并进行双向测试。例如,如下所示:

Public Function ParseId(id As String) As ParsedId
    Dim number As Integer
    If id?.Length > 0 Then
        If Integer.TryParse(id, number) Then
            Return New ParsedId() With {
                .Number = number }
        End If
    End If
    If id?.Length > 1 Then
        If Char.IsLetter(id(0)) And Integer.TryParse(id.Substring(1), number) Then
            Return New ParsedId() With {
                    .Letter = id(0),
                    .Number = number }
        End If
    End If
    Return Nothing
End Function


Public Class ParsedId
    Public Property Letter As String
    Public Property Number As Integer
End Class

但是,如果将来有可能需要使其变得更加灵活,那么您可能要考虑使用regex(反之则更短):

Public Function ParseId(id As String) As ParsedId
    Dim m As Match = Regex.Match(id, "^(?<Letter>[A-Z])?(?<Number>\d+)$")
    If m.Success Then
        Return New ParsedId With {
            .Letter = m.Groups("Letter").Value,
            .Number = Integer.Parse(m.Groups("Number").Value) }
    Else
        Return Nothing
    End If
End Function