2012-09-28 40 views
0

我在Vb.net中創建了一個簡單的應用程序,我需要執行某些驗證。所以我想要一個名稱文本框只接受來自a-z和A-Z的字符。獲取文本框只接受vb.net中的字符

爲此,我寫了下面的代碼:

Private Sub txtname_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox5.KeyPress 
    If Asc(e.KeyChar) <> 8 Then 
     If Asc(e.KeyChar) > 65 Or Asc(e.KeyChar) < 90 Or Asc(e.KeyChar) > 96 Or Asc(e.KeyChar) < 122 Then 
      e.Handled = True 
     End If 
    End If 
End Sub 

但不知何故,它沒有讓我輸入字符。當我嘗試輸入任何角色時,它什麼也不做。

什麼原因導致了這個問題,我該如何解決?

回答

5

或者,你可以做這樣的事情,

Private Sub TextBox1_KeyPress(sender As Object, e As KeyPressEventArgs) _ 
           Handles txtName.KeyPress 

    If Not (Asc(e.KeyChar) = 8) Then 
     Dim allowedChars As String = "abcdefghijklmnopqrstuvwxyz" 
     If Not allowedChars.Contains(e.KeyChar.ToString.ToLower) Then 
      e.KeyChar = ChrW(0) 
      e.Handled = True 
     End If 
    End If 

End Sub 

,或者如果你還是想ASCII方式,試試這個,

Private Sub TextBox1_KeyPress(sender As Object, e As KeyPressEventArgs) Handles txtName.KeyPress 

    If Not (Asc(e.KeyChar) = 8) Then 
     If Not ((Asc(e.KeyChar) >= 97 And Asc(e.KeyChar) <= 122) Or (Asc(e.KeyChar) >= 65 And Asc(e.KeyChar) <= 90)) Then 
      e.KeyChar = ChrW(0) 
      e.Handled = True 
     End If 
    End If 

End Sub 

都將具有相同的行爲。

+0

但即使代碼至極我寫shd工作....你認爲有issum概率wid代碼? – EqEdi

+1

@EqEdi你的代碼不會工作,因爲你的條件混亂了,導致編譯器混淆:D –

+0

@JohnWoo很好的解決方案。改編並鏈接在http://stackoverflow.com/questions/41151574/automatically-remove-not-authorized-character-on-regular-expressions-just-after/ – fedeteka

0

私人小組txtname_KeyPress(BYVAL發件人爲對象,BYVALË作爲System.Windows.Forms.KeyPressEventArgs)處理TextBox5.KeyPress

If AscW(e.KeyChar) > 64 And AscW(e.KeyChar) < 91 Or AscW(e.KeyChar) > 96 And AscW(e.KeyChar) < 123 Or AscW(e.KeyChar) = 8 Then 
    Else 
     e.KeyChar = Nothing 
    End If 

末次

我希望這有助於!

0

這是一個更抽象的方法,但仍然有效。它很簡單,只需添加到TextChanged事件即可。您可以通過將其句柄添加到子文件夾並使用DirectCast()將其與多個文本框一起使用。

Dim allowed As String = ("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ") 
     For Each c As Char In TextBox.Text 
      If allowed.Contains(c) = False Then 
       TextBox.Text = TextBox.Text.Remove(TextBox.SelectionStart - 1, 1) 
       TextBox.Select(TextBox.Text.Count, 0) 
      End If 
     Next 

摘要:如果輸入無效字符,它會立即被刪除(大部分時間的字符將不可見足夠長的用戶通知)。

-1
Private Sub txtStudentName_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtStudentName.KeyPress 

    If Not Char.IsLetter(e.KeyChar) And Not e.KeyChar = Chr(Keys.Delete) And Not e.KeyChar = Chr(Keys.Back) And Not e.KeyChar = Chr(Keys.Space) Then 

     e.Handled = True 

    End If 

End Sub 
+0

通常,不要將代碼放在註釋中。 [編輯]你的答案,並確保你使用代碼塊格式來提高可讀性。 –

相關問題