2010-01-15 7 views
0

사용자가 아무런 기호 (예 :)를 입력 할 수 없도록 텍스트 상자의 서식을 지정하려고합니다. ; ' "£의 $의 %^[] {}VB.net에서 텍스트 상자 서식 지정

If (Char.IsDigit(e.KeyChar) Or Char.IsControl(e.KeyChar) Or (e.KeyChar = ".")) Then 
      e.Handled = True 

End if 

이 코드는 숫자 또는 정수를 입력으로부터 사용자를 방지 할 수 있습니다.하지만 어떻게 문자를 방지 할 수 있습니까?

사전에 감사합니다.

+0

잊지 말라가있는 경우 복사 앤 다음과 같이 형태로 사용 다음은 코드의 VB.NET 버전입니다 텍스트 상자에 코드를 붙여 넣으면 개별 문자가 선택되지 않으므로 유효성 검사를 위해이 코드를 단독으로 사용하지 마십시오. – MartW

+0

@klausbyskov 게시가 허용되지 않는 것 대신 허용되는 것을 말하기가 일반적입니다. 클럽에서 경비원처럼, "앨리스 인이나 밥, 찰리를 허용하지 마세요 ..."대신 "이 (x) 사람들은 들어오고 다른 누구도 들어올 수 없습니다"라고 말하기가 훨씬 쉽습니다. –

답변

1

을하는 방법에 대한

Not Char.IsLetter(e.KeyChar) 

?

0
또한 아약스에서 "마스크 편집"을 사용할 수 있습니다

. 아약스 컨트롤 툴킷이 될 수 있습니다

http://www.asp.net/ajax/ajaxcontroltoolkit/Samples/MaskedEdit/MaskedEdit.aspx

가 아약스를 설치에서 발견했다. Visual Studio에 AJAX 컨트롤을 추가하는 방법에 대한 웹 사이트의 단계를 따르십시오. 그런 다음 "MaskedEditExtender"컨트롤을 서식을 지정할 텍스트 상자로 드래그하십시오.

말한다 속성 필드에

나는 내가 디자인보기 끌어에서 "TollkitScriptManager"라고 무언가를 추가하고 위의 컨트롤을 드롭했다는 것을 발견 이후 (999) 999-9999

를 입력 "마스크" 형식화를 원하는 텍스트 상자 인 txtbox.이 속성을 변경하지 않아도된다고 생각합니다.이 컨트롤은 서식을 지정할 텍스트 상자 위에 있어야한다고 생각합니다.

이것은 사용자가 찾고자하는 것일 수도 있고 그렇지 않을 수도 있지만 텍스트 상자에 매우 특정한 형식을 허용하고 사용자가 선택한 번호 만 입력하도록합니다. 이것은 텍스트 상자에 전화 번호를 서식을 지정하는 데 매우 유용합니다.

0

나는 이것을 previous question에서 수행하기위한 간단한 클래스를 작성했습니다.

Public Class TextBoxFilter 
    <Flags()> Public Enum Filters 
     None = 0 
     Text = 1 
     Numbers = 2 
     AlphaNumeric = Filters.Text Or Filters.Numbers 
     Currency = 4 
     All = Filters.Text Or Filters.Numbers Or Filters.Currency 
    End Enum 

    Dim _keyFilter As Dictionary(Of TextBox, Filters) 
    Dim _allowedKeys As Dictionary(Of TextBox, String) 
    Dim _invalidKeys As Dictionary(Of TextBox, String) 
    Dim _keyEventArgs As Dictionary(Of TextBox, Windows.Forms.KeyEventArgs) 

    Private Shared DecimalMark As String = Application.CurrentCulture.NumberFormat.NumberDecimalSeparator 
    Private Shared NegativeMark As String = Application.CurrentCulture.NumberFormat.NegativeSign 
    Private Shared CurrencySymb As String = Application.CurrentCulture.NumberFormat.CurrencySymbol 
    Private Shared CurrencyDecimal As String = Application.CurrentCulture.NumberFormat.CurrencyDecimalSeparator 


    Public Sub New() 
     _keyFilter = New Dictionary(Of TextBox, Filters) 
     _allowedKeys = New Dictionary(Of TextBox, String) 
     _invalidKeys = New Dictionary(Of TextBox, String) 
     _keyEventArgs = New Dictionary(Of TextBox, KeyEventArgs) 
    End Sub 

    'set & remove filter' 

    Public Sub SetTextBoxFilter(ByVal textBox As TextBox, ByVal filter As Filters) 
     SetTextBoxFilter(textBox, filter, AllowedKeys(textBox), InvalidKeys(textBox)) 
    End Sub 

    Public Sub SetTextBoxFilter(ByVal textBox As TextBox, ByVal allowedKeys As String) 
     SetTextBoxFilter(textBox, Filter(textBox), allowedKeys, InvalidKeys(textBox)) 
    End Sub 

    Public Sub SetTextBoxFilter(ByVal textBox As TextBox, _ 
    ByVal allowedKeys As String, ByVal invalidKeys As String) 

     SetTextBoxFilter(textBox, Filter(textBox), allowedKeys, invalidKeys) 
    End Sub 

    Public Sub SetTextBoxFilter(ByVal textBox As TextBox, ByVal filter As Filters, _ 
    ByVal allowedKeys As String, ByVal invalidKeys As String) 

     If Not _keyFilter.ContainsKey(textBox) Then 
      'add the textbox and its filter if it does not exist in ' 
      'the collection of registered textboxes     ' 
      _keyFilter.Add(textBox, filter) 
      _allowedKeys.Add(textBox, allowedKeys) 
      _invalidKeys.Add(textBox, invalidKeys) 
      _keyEventArgs.Add(textBox, New System.Windows.Forms.KeyEventArgs(Keys.None)) 

      'add the event handlers         ' 
      AddHandler textBox.KeyDown, AddressOf KeyDownUp 
      AddHandler textBox.KeyUp, AddressOf KeyDownUp 
      AddHandler textBox.KeyPress, AddressOf KeyPress 
      AddHandler textBox.Validating, AddressOf Validating 
      AddHandler textBox.Disposed, AddressOf Disposed 

     Else 
      'change the filter of the textbox if it exists in  ' 
      'the collection of registered textboxes     ' 
      _keyFilter(textBox) = filter 
      _allowedKeys(textBox) = allowedKeys 
      _invalidKeys(textBox) = invalidKeys 
     End If 
    End Sub 

    Public Sub RemoveTextBoxFilter(ByVal textBox As TextBox) 
     If _keyFilter.ContainsKey(textBox) Then 
      _keyFilter.Remove(textBox) 
      _allowedKeys.Remove(textBox) 
      _invalidKeys.Remove(textBox) 
      _keyEventArgs.Remove(textBox) 

      RemoveHandler textBox.KeyDown, AddressOf KeyDownUp 
      RemoveHandler textBox.KeyUp, AddressOf KeyDownUp 
      RemoveHandler textBox.KeyPress, AddressOf KeyPress 
      RemoveHandler textBox.Validating, AddressOf Validating 
      RemoveHandler textBox.Disposed, AddressOf Disposed 
     End If 
    End Sub 

    Public Function ContainsTextBox(ByVal textBox As TextBox) As Boolean 
     Return _keyFilter.ContainsKey(textBox) 
    End Function 

    'properties' 

    Public Property Filter(ByVal textBox As TextBox) As Filters 
     Get 
      If ContainsTextBox(textBox) Then 
       Return _keyFilter.Item(textBox) 
      Else 
       Return Filters.None 
      End If 
     End Get 
     Set(ByVal value As Filters) 
      SetTextBoxFilter(textBox, value) 
     End Set 
    End Property 

    Public Property AllowedKeys(ByVal textBox As TextBox) As String 
     Get 
      If ContainsTextBox(textBox) Then 
       Return _allowedKeys(textBox) 
      Else 
       Return "" 
      End If 
     End Get 
     Set(ByVal value As String) 
      SetTextBoxFilter(textBox, Me.Filter(textBox), value, Me.InvalidKeys(textBox)) 
     End Set 
    End Property 

    Public Property InvalidKeys(ByVal textBox As TextBox) As String 
     Get 
      If ContainsTextBox(textBox) Then 
       Return _invalidKeys(textBox) 
      Else 
       Return "" 
      End If 
     End Get 
     Set(ByVal value As String) 
      SetTextBoxFilter(textBox, Me.Filter(textBox), Me.AllowedKeys(textBox), value) 
     End Set 
    End Property 

    'event handlers' 

    Private Sub Disposed(ByVal sender As Object, ByVal e As System.EventArgs) 
     RemoveTextBoxFilter(DirectCast(sender, TextBox)) 
    End Sub 

    Private Sub KeyDownUp(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) 
     'assign the modifiers' 
     _keyEventArgs(DirectCast(sender, TextBox)) = e 
    End Sub 

    Private Sub KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) 
     'ensure key pressed is in the allowed keys' 

     Dim txt = DirectCast(sender, TextBox) 
     Dim c = e.KeyChar 
     Dim allowKey As Boolean = IsValidChar(txt, c, txt.SelectionStart) 


     'check for backspace & Ctrl combinations if the allowKey is still false' 
     If allowKey = False Then 
      If _keyEventArgs(txt).Control Then 
       'control modifier goes with A, X, C, V and Z for ' 
       'Select All, Cut, Copy, Paste and Undo respectively' 
       Dim key = _keyEventArgs(txt).KeyCode 
       allowKey = (key = Keys.A OrElse key = Keys.X OrElse _ 
        key = Keys.C OrElse key = Keys.V OrElse key = Keys.Z) 

      ElseIf _keyEventArgs(txt).KeyCode = Keys.Back Then 
       'allow the backspace key' 
       allowKey = True 
      End If 
     End If 


     'disable the key if it was not valid' 
     If Not allowKey Then 
      e.Handled = True 
      Beep() 
     End If 
    End Sub 

    Private Sub Validating(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) 
     Dim box = DirectCast(sender, TextBox) 
     Dim boxFlags = _keyFilter(box) 

     'skip validation if the textbox allows all entries or there is no text' 
     If boxFlags = Filters.All Or box.Text = "" Then Exit Sub 

     'otherwise check the characters entered' 
     Dim txtChars = box.Text.ToCharArray 

     Dim isValidEntry As Boolean = False 

     'check each caracter for an invalid entry' 
     For i = 0 To txtChars.Length - 1 
      Dim c = txtChars(i) 
      isValidEntry = IsValidChar(box, txtChars(i), i) 

      If Not isValidEntry Then 
       box.Select(i, 1) 
       Exit For 
      End If 
     Next 

     If Not isValidEntry Then e.Cancel = True 

     If Not isValidEntry Then 
      MsgBox("The text entered is invalid for the format " & boxFlags.ToString & "." & _ 
      If(_allowedKeys(box) <> "", vbCrLf & "Additional Allowed Keys: " & _allowedKeys(box), "") & _ 
      If(_invalidKeys(box) <> "", vbCrLf & "Additional Invalid Keys: " & _invalidKeys(box), ""), _ 
      MsgBoxStyle.Critical, "Invalid Entry") 
     End If 
    End Sub 

    Private Function IsValidChar(ByVal textBox As TextBox, ByVal c As Char, ByVal charIndex As Integer) As Boolean 
     'ensure key pressed is in the allowed keys ' 

     Dim pF = _keyFilter(textBox) 
     Dim aK = _allowedKeys(textBox) 
     Dim iK = _invalidKeys(textBox) 
     Dim shouldAllow As Boolean = False 


     'if filter is set to all, return true unconditionally ' 
     If pF = Filters.All Then Return True 


     'check preset filters ' 

     'check for text ' 
     If EnumHasFlag(pF, Filters.Text) Then 
      If Not Char.IsDigit(c) Then 
       shouldAllow = True 
      Else 
       'if the character is a digit, check for the number flag (AlphaNumerics) ' 
       If EnumHasFlag(pF, Filters.Numbers) Then 
        shouldAllow = True 
       End If 
      End If 

     End If 

     'check for numbers ' 
     If shouldAllow = False AndAlso EnumHasFlag(pF, Filters.Numbers) Then 
      If Char.IsDigit(c) Then 
       shouldAllow = True 
      ElseIf DecimalMark.Contains(c) Then 
       'allow the decimal if there is no decimal in the textbox's 
       'text or the selected text contains the mark' 
       If Not textBox.Text.Contains(c) OrElse textBox.SelectedText.Contains(c) Then 
        shouldAllow = True 
       End If 
      ElseIf NegativeMark.Contains(c) AndAlso _ 
       (charindex <= NegativeMark.IndexOf(c)) Then 
       'allow the negative mark if we are at the start of the' 
       'textbox' 
       shouldAllow = True 
      End If 

     End If 

     'check for currency ' 
     If shouldAllow = False AndAlso EnumHasFlag(pF, Filters.Currency) Then 
      If Char.IsDigit(c) Then 
       shouldAllow = True 
      ElseIf CurrencyDecimal.Contains(c) Then 
       'allow the currency decimal mark if it does not exist in the ' 
       'textbox''s text or the selected text contains the mark ' 
       If Not textBox.Text.Substring(0, charIndex).Contains(c) OrElse _ 
        textBox.SelectedText.Contains(c) Then 
        shouldAllow = True 
       End If 
      ElseIf CurrencySymb.Contains(c) AndAlso _ 
       (charIndex <= CurrencySymb.IndexOf(c)) Then 
       'allow the currency symbol if we are in a valid position' 
       shouldAllow = True 
      End If 

     End If 



     'now check for extra allowed keys' 
     If Not shouldAllow Then 
      shouldAllow = aK.Contains(c) 
     End If 

     'and then check for extra invalid keys' 
     If shouldAllow AndAlso iK.Contains(c) Then 
      shouldAllow = False 
     End If 


     Return shouldAllow 
    End Function 

    <System.Diagnostics.DebuggerStepThrough()> _ 
    Private Function EnumHasFlag(ByVal value As [Enum], ByVal flag As [Enum]) As Boolean 
     Return (Convert.ToInt64(value) And Convert.ToInt64(flag)) = Convert.ToInt64(flag) 
    End Function 
End Class 

그냥 프로젝트에서이 클래스를 배치하고

Public Class Form1 

    Dim filter = New TextBoxFilter() 

    Private Sub Form1_Load(object sender, System.EventArgs e) Handles MyBase.Load 
     filter.SetTextBoxFilter(TextBox1, TextBoxFilter.Filters.Numbers) 
    End Sub 
End Class 
관련 문제