【问题标题】:how can i limit inputbox to 11 numerical values in vb如何在vb中将输入框限制为11个数值
【发布时间】:2017-06-16 13:33:50
【问题描述】:

如何在 vb 中将输入框限制为 11 个数值?我想让某人编辑电话号码,但我当前的代码似乎有问题。

 Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    For Each x As ListViewItem In lvCustomers.Items
        Dim contactEdit As String
        If x.Checked Then
            contactEdit = CInt(InputBox("Modify contact no."))
            Do Until contactEdit.Count = 11
                MessageBox.Show("Maximum numerical digits of 11")
            Loop

            x.SubItems(5).Text = contactEdit

            x.Checked = False

        End If
    Next
End Sub

【问题讨论】:

标签: vb.net inputbox


【解决方案1】:

您可以使用 Regex 来检查:

Imports System.Text.RegularExpressions
'[...]
Dim isValid As Boolean = Regex.Match("12345", "^\d{0,11}$").Success()

您的代码可能如下所示:

Imports System.Text.RegularExpressions
'[...]
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    For Each x As ListViewItem In lvCustomers.Items
        Dim contactEdit As String

        If x.Checked Then
            contactEdit = InputBox("Modify contact no.")

            Do Until Regex.Match(contactEdit, "^\d{0,11}$").Success()
                MessageBox.Show("Maximum numerical digits of 11")
                contactEdit = InputBox("Modify contact no.")
            Loop

            x.SubItems(5).Text = contactEdit
            x.Checked = False
        End If
    Next
End Sub

您可以在 RegExp ({minValue,maxValue}) 上定义输入的最小和最大长度。输入必须是数字 (\d)。你可以在这个网站上找到使用的 RegExp 的解释:https://regex101.com/r/6h7z2u/1

提示:我建议从InputBox 中删除CInt,因为如果InputBox 中的值不是有效的整数,代码会抛出Exception。使用解决方案的正则表达式,只能将数字写入InputBox

【讨论】:

  • 感谢您的代码。我在页面顶部声明了 Imports System.Text.RegularExpressions。代码“正则表达式”中的部分带有下划线,并表示未声明。有什么建议吗?
  • 如果你使用Import,你必须删除Regex前面的RegularExpressions.。从RegularExpressions.RegexRegex。查看我的更新。
【解决方案2】:

您可以使用 Len(contactEdit.Text) = 11 代替 contactEdit.Count = 11

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    For Each x As ListViewItem In lvCustomers.Items
        Dim contactEdit As String
        If x.Checked Then
            contactEdit = CInt(InputBox("Modify contact no."))
            Do Until Len(contactEdit.Text) >= 11
                MessageBox.Show("Maximum numerical digits of 11")
            Loop
            x.SubItems(5).Text = contactEdit
            x.Checked = False
        End If
    Next
End Sub

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-14
    相关资源
    最近更新 更多