2017-06-16 65 views
1

如何限制輸入框在vb中的11個數值?我想讓一個人編輯一個電話號碼,但似乎與我目前的代碼有問題。如何限制輸入框爲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 
+0

https://stackoverflow.com/questions/20686928/input-box-limit- in-vb –

+0

https://msdn.microsoft.com/en-us/library/system.windows.forms.maskedtextbox.mask – Slai

回答

1

您可以使用正則表達式來檢查:

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 

您可以在正則表達式定義了輸入的最小和最大長度({minValue,maxValue})。輸入必須是數字(\d)。您可以在這個網站找到使用正則表達式的解釋:https://regex101.com/r/6h7z2u/1

提示:我建議,因爲代碼引發Exception如果從InputBox值不是一個有效的整數從InputBox刪除CInt。通過使用解決方案的RegExp,只能將數字寫入InputBox

+0

謝謝你的代碼。我在頁面頂部聲明瞭Imports System.Text.RegularExpressions。代碼「regularexpressions」中的部分是下劃線,並表示它沒有聲明。有什麼建議麼? – James

+0

如果您使用'Import',則必須刪除'Regex'前面的'RegularExpressions.'。從'RegularExpressions.Regex'到'Regex'。查看我的更新。 –

0

可以使用萊恩(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 
相關問題