visual basic:用户在文本后输入一个 % 符号

visual basic: user inputs a % sign after text

Private Sub btnBillSearch_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnBillSearch.Click

        If Me.txbBILL_NR.Text = "" Or Me.txbBILL_NR.TextLength >= 4 Then
            Try
                Search()

                If Me.bsBillGrid.Current IsNot Nothing Then
                    Me.dgvBill.Focus()
                End If
            Catch ex As Exception
                Utility.ExceptionManager.HandleException(ex)
            End Try
        Else
            MessageBox.Show("enter at least 4 numbers")
        End If
    End Sub

我的应用程序中有这种搜索按钮的方法。 所以,我已经写了用户输入最少字符数的 If 条件是 4 到 select 个条目。

我需要再验证一次 % 符号。我想通了,那有点像 startWidth(),但我不明白我是如何得到这些情况的:

我考虑使用 startWith/endWith 或正则表达式。 谁能给我一些建议去哪里看。

  1. 用户在txbBILL_NR后添加“%”符号——系统不会在后台添加额外的“%”, txbBILL_NR 找到并反映在列表中的相同部件号。

  2. 用户没有在txbBILL_NR后面加“%”符号——系统在后台额外加了一个“%”, txbBILL_NR 相同编号。找到并列出零件。 “%”字符不需要用户表示;

3.user在txbBILL_NR的开头或中间添加了“%”符号——系统不会在后台额外添加“%”, txbBILL_NR 找到并反映在列表中(无需更改);

  1. 如果用户在txbBILL_NR字段中输入了至少4个字符(假设发票号不能短于4个字符),则只需要标记“%”系统。

  2. 如果用户至少输入了4个字符(无论是起始字符还是从中间开始),并且在这些符号的开头或中间添加了“%”,系统不会添加背景中额外的“%” 找到具有相同部分(符号)部分的发票并反映在列表中。

'Get raw user entry.
Dim searchText = txbBILL_NR.Text

'Get user entry without wildcards.
Dim cleanSearchText = searchText.Replace("%", String.Empty)

If cleanSearchText.Length = 0 OrElse cleanSearchText.Length >= 4 Then
    If searchText = cleanSearchText Then
        'There are no wildcards so append one.
        searchText &= "%"
    End If

    'Use searchText here.
End If

我觉得这个功能符合你的要求

Private Function SearchCriterium(ByVal Crit As String) As String
    ' 295
    
    Const Mark  As String = "%"
    Dim Fun     As String           ' function return value
    
    Fun = Crit
    Do While (Len(Fun) >= 4) And (Right(Fun, 1) = Mark)
        Fun = Left(Fun, Len(Fun) - 1)
    Loop
    If Len(Fun) < 4 Then
        MsgBox "Enter at least 4 characters.", _
                vbExclamation, "Invalid search crterium"
         SearchCriterium = Crit
    Else
        If InStr(Fun, Mark) = 0 Then Fun = Fun & Mark
    End If
    SearchCriterium = Replace(Fun, Mark, "*")
End Function

观察它用 VBA 的通配符 * 替换了 % 符号。如果您当时不需要该功能,可以将其删除。

该函数删除任何现有的尾随占位符,然后如果 none 存在于字符串的其他位置则添加一个。这是我 运行.

的测试列表
Private Sub Test_SearchCriterium()
    Debug.Print SearchCriterium("Item")
    Debug.Print SearchCriterium("It%em")
    Debug.Print SearchCriterium("%Item")
    Debug.Print SearchCriterium("Ite%")
    Debug.Print SearchCriterium("It%%")
End Sub