locked
vb.net not to accept comma, single quote and double quote RRS feed

  • Question

  • Hi !

    I need to filter my all my textbox in my program to accept

    all characters except for  comma, single quote, and double quote. (, ' ").

    I use the keypress event for this filter. Here is my initial code but is not working.

    If (e.KeyChar = Keys.OemQuotes) Then
            e.handled = false
        Else
    
       End If

    In this, if they key entered is a quote then it will not allow.

    Something like this and also to include keys.oemcomma.

    I need to filter this to prevent error in my database query since comma and quotes are sensitive to it.

    Any help is much appreciated!

    Thanks,

    Pem

    • Moved by Amanda Zhu Monday, August 12, 2013 7:47 AM
    Saturday, August 10, 2013 5:56 AM

Answers

  • Hello,

    The following component works similar to a ToolTip, it implements IExtenderProvider Interface and works with TextBox controls only (see function CanExtend logic).

    Build your project, open a form, in the toolbox you will see the component at the top of the toolbox. Double click it once which will place one instance in the window below the form. Select any TextBox, at the bottom of the property window there is a category "Type Validator" with a property "SpecialCharacters" which is pre-filled with your two characters. Build/run the project, each TextBox on the form will not allow these two characters. If one or more should allow these characters simple select the TextBox and remove the two characters.

    Note there is other functionality which you need not be concerned with but feel free to explore.

    Place into a new file named KeyPressValidator.vb

    Option Explicit On
    Option Strict On
    Option Compare Text
    Imports System.ComponentModel
    Imports System.Windows.Forms
    #Region "Enums"
    Public Enum CharsAllowSpecialChars
        [None] = 0
        [InList] = 1
        [NotInList] = 2
    End Enum
    #End Region
    <Drawing.ToolboxBitmap(GetType(System.Windows.Forms.TextBox)), _
    System.ComponentModel.DesignerCategoryAttribute("Code"), _
    ProvideProperty("AllowAlpha", GetType(Control)), _
    ProvideProperty("AllowNumeric", GetType(Control)), _
    ProvideProperty("AllowSpecialChars", GetType(Control)), _
    ProvideProperty("SpecialCharacters", GetType(Control))> _
    Public Class KeyPressValidator
        Inherits System.ComponentModel.Component
        Implements IExtenderProvider
        'This hash table stores all the controls extended by this extender provider
        Friend htProvidedProperties As New Hashtable
    #Region "IExtenderProvider"
        ''' <summary>
        ''' The Property should be Extend / Not for the TextBox classes
        ''' </summary>
        ''' <param name="extendee"></param>
        ''' <returns></returns>
        ''' <remarks></remarks>
        Public Function CanExtend(ByVal extendee As Object) As Boolean Implements System.ComponentModel.IExtenderProvider.CanExtend
          If (TypeOf extendee Is TextBox) OrElse (TypeOf extendee Is MaskedTextBox) Then
             Return True
          Else
             Return False
          End If
        End Function
    #End Region
    #Region "Extensible Properties"
        Private Class KeyValidatorProperties
            Public AllowAlpha As Boolean = True
            Public AllowNumeric As Boolean = True
            Public AllowSpecialChars As CharsAllowSpecialChars = CharsAllowSpecialChars.NotInList
            ' KSG normally this would be set in the IDE property window for each TextBox but
            ' here I default the array to have two characters for a post
            ' http://social.msdn.microsoft.com/Forums/vstudio/en-US/fe3c2ac8-ca67-4393-9d60-4d202bd83b55/vbnet-not-to-accept-comma-single-quote-and-double-quote
            Public SpecialCharacters() As Char = ",'".ToCharArray
        End Class
        <Category("Type Validator")> _
        Sub SetAllowAlpha(ByVal ctrl As Control, ByVal value As Boolean)
            GetControlFromHashtable(ctrl).AllowAlpha = value
        End Sub
        <Category("Type Validator")> _
        Function GetAllowAlpha(ByVal ctrl As Control) As Boolean
            Return GetControlFromHashtable(ctrl).AllowAlpha
        End Function
        <Category("Type Validator")> _
        Sub SetAllowNumeric(ByVal ctrl As Control, ByVal value As Boolean)
            GetControlFromHashtable(ctrl).AllowNumeric = value
        End Sub
        <Category("Type Validator")> _
        Function GetAllowNumeric(ByVal ctrl As Control) As Boolean
            Return GetControlFromHashtable(ctrl).AllowNumeric
        End Function
        <Category("Type Validator")> _
        Sub SetAllowSpecialChars(ByVal ctrl As Control, ByVal value As CharsAllowSpecialChars)
            GetControlFromHashtable(ctrl).AllowSpecialChars = value
        End Sub
        <Category("Type Validator")> _
        Function GetAllowSpecialChars(ByVal ctrl As Control) As CharsAllowSpecialChars
            Return GetControlFromHashtable(ctrl).AllowSpecialChars
        End Function
        <Category("Type Validator")> _
        Sub SetSpecialCharacters(ByVal ctrl As Control, ByVal value As String)
            GetControlFromHashtable(ctrl).SpecialCharacters = value.ToCharArray
        End Sub
        <Category("Type Validator")> _
        Function GetSpecialCharacters(ByVal ctrl As Control) As String
            Return CType(GetControlFromHashtable(ctrl).SpecialCharacters, String)
        End Function
    #End Region
    #Region "Behavior"
        Private Function GetControlFromHashtable(ByVal ctrl As Control) As KeyValidatorProperties
            If htProvidedProperties.Contains(ctrl) Then
                Return DirectCast(htProvidedProperties(ctrl), KeyValidatorProperties)
            Else
                Dim ProvidedProperties As New KeyValidatorProperties
                'Add A KeyPress Event Handler as the control is added to hash table
                AddHandler ctrl.KeyPress, AddressOf KeyPressHandler
                AddHandler ctrl.TextChanged, AddressOf TextChangedHandler
                htProvidedProperties.Add(ctrl, ProvidedProperties)
                Return ProvidedProperties
            End If
        End Function
       '+++KSG  10/8/2008 1:53:04 PM changed from TextBox to TextBoxBase
       Private Function CleanText(ByVal txtSender As TextBoxBase, ByVal origText As String) As String
          Dim bAlpha As Boolean = GetControlFromHashtable(txtSender).AllowAlpha
          Dim bDigit As Boolean = GetControlFromHashtable(txtSender).AllowNumeric
          Dim bChars As CharsAllowSpecialChars = GetControlFromHashtable(txtSender).AllowSpecialChars
          Dim SpecialCharacters() As Char = GetControlFromHashtable(txtSender).SpecialCharacters
          Dim index As Integer
          Dim sRet As String = ""
          While index < origText.Length
             Dim bCancel As Boolean = True
             Dim character As Char = origText(index)
             If Char.IsControl(character) Then
                bCancel = False
             ElseIf Char.IsLetter(character) AndAlso bAlpha = False Then
                bCancel = True
             ElseIf Char.IsDigit(character) AndAlso bDigit = False Then
                bCancel = True
             ElseIf bChars = CharsAllowSpecialChars.None AndAlso Char.IsLetter(character) = False AndAlso Char.IsDigit(character) = False Then
                bCancel = True
             ElseIf bChars = CharsAllowSpecialChars.NotInList AndAlso Array.IndexOf(SpecialCharacters, character) >= 0 AndAlso Char.IsLetter(character) = False AndAlso Char.IsDigit(character) = False Then
                bCancel = True
             ElseIf bChars = CharsAllowSpecialChars.InList AndAlso Array.IndexOf(SpecialCharacters, character) < 0 AndAlso Char.IsLetter(character) = False AndAlso Char.IsDigit(character) = False Then
                bCancel = True
             Else
                bCancel = False
             End If
             If bCancel = False Then
                sRet &= character
             End If
             index += 1
          End While
          Return sRet
       End Function
        Private Sub TextChangedHandler(ByVal sender As System.Object, ByVal e As System.EventArgs)
          '+++KSG  10/8/2008 1:52:43 PM changed from TextBox to TextBoxBase
          Dim txtSender As TextBoxBase = CType(sender, TextBoxBase)
            Dim sChangedString As String = txtSender.Text
            Dim sCleanString As String = CleanText(txtSender, sChangedString)
            If sChangedString <> sCleanString Then
                txtSender.Text = sCleanString
            End If
        End Sub
        Private Sub KeyPressHandler(ByVal sender As Object, ByVal e As KeyPressEventArgs)
          '+++KSG  10/8/2008 1:51:56 PM changed from TextBox to TextBoxBase
          Dim txtSender As TextBoxBase = CType(sender, TextBoxBase)
            If txtSender.ReadOnly = True Then
                If Char.IsControl(e.KeyChar) Then
                    e.Handled = False
                Else
                    e.Handled = True
                End If
            Else
                If Char.IsControl(e.KeyChar) Then
                    e.Handled = False
                ElseIf Char.IsLetter(e.KeyChar) AndAlso GetControlFromHashtable(txtSender).AllowAlpha = False Then
                    e.Handled = True
                ElseIf Char.IsDigit(e.KeyChar) AndAlso GetControlFromHashtable(txtSender).AllowNumeric = False Then
                    e.Handled = True
                ElseIf GetControlFromHashtable(txtSender).AllowSpecialChars = CharsAllowSpecialChars.None AndAlso Char.IsLetter(e.KeyChar) = False AndAlso Char.IsDigit(e.KeyChar) = False Then
                    e.Handled = True
                ElseIf GetControlFromHashtable(txtSender).AllowSpecialChars = CharsAllowSpecialChars.NotInList AndAlso Array.IndexOf(GetControlFromHashtable(txtSender).SpecialCharacters, e.KeyChar) >= 0 AndAlso Char.IsLetter(e.KeyChar) = False AndAlso Char.IsDigit(e.KeyChar) = False Then
                    e.Handled = True
                ElseIf GetControlFromHashtable(txtSender).AllowSpecialChars = CharsAllowSpecialChars.InList AndAlso Array.IndexOf(GetControlFromHashtable(txtSender).SpecialCharacters, e.KeyChar) < 0 AndAlso Char.IsLetter(e.KeyChar) = False AndAlso Char.IsDigit(e.KeyChar) = False Then
                    e.Handled = True
                Else
                    e.Handled = False
                End If
            End If
        End Sub
    #End Region
    End Class


    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem.

    Saturday, August 10, 2013 11:41 AM

All replies

  • Hello,

    The following component works similar to a ToolTip, it implements IExtenderProvider Interface and works with TextBox controls only (see function CanExtend logic).

    Build your project, open a form, in the toolbox you will see the component at the top of the toolbox. Double click it once which will place one instance in the window below the form. Select any TextBox, at the bottom of the property window there is a category "Type Validator" with a property "SpecialCharacters" which is pre-filled with your two characters. Build/run the project, each TextBox on the form will not allow these two characters. If one or more should allow these characters simple select the TextBox and remove the two characters.

    Note there is other functionality which you need not be concerned with but feel free to explore.

    Place into a new file named KeyPressValidator.vb

    Option Explicit On
    Option Strict On
    Option Compare Text
    Imports System.ComponentModel
    Imports System.Windows.Forms
    #Region "Enums"
    Public Enum CharsAllowSpecialChars
        [None] = 0
        [InList] = 1
        [NotInList] = 2
    End Enum
    #End Region
    <Drawing.ToolboxBitmap(GetType(System.Windows.Forms.TextBox)), _
    System.ComponentModel.DesignerCategoryAttribute("Code"), _
    ProvideProperty("AllowAlpha", GetType(Control)), _
    ProvideProperty("AllowNumeric", GetType(Control)), _
    ProvideProperty("AllowSpecialChars", GetType(Control)), _
    ProvideProperty("SpecialCharacters", GetType(Control))> _
    Public Class KeyPressValidator
        Inherits System.ComponentModel.Component
        Implements IExtenderProvider
        'This hash table stores all the controls extended by this extender provider
        Friend htProvidedProperties As New Hashtable
    #Region "IExtenderProvider"
        ''' <summary>
        ''' The Property should be Extend / Not for the TextBox classes
        ''' </summary>
        ''' <param name="extendee"></param>
        ''' <returns></returns>
        ''' <remarks></remarks>
        Public Function CanExtend(ByVal extendee As Object) As Boolean Implements System.ComponentModel.IExtenderProvider.CanExtend
          If (TypeOf extendee Is TextBox) OrElse (TypeOf extendee Is MaskedTextBox) Then
             Return True
          Else
             Return False
          End If
        End Function
    #End Region
    #Region "Extensible Properties"
        Private Class KeyValidatorProperties
            Public AllowAlpha As Boolean = True
            Public AllowNumeric As Boolean = True
            Public AllowSpecialChars As CharsAllowSpecialChars = CharsAllowSpecialChars.NotInList
            ' KSG normally this would be set in the IDE property window for each TextBox but
            ' here I default the array to have two characters for a post
            ' http://social.msdn.microsoft.com/Forums/vstudio/en-US/fe3c2ac8-ca67-4393-9d60-4d202bd83b55/vbnet-not-to-accept-comma-single-quote-and-double-quote
            Public SpecialCharacters() As Char = ",'".ToCharArray
        End Class
        <Category("Type Validator")> _
        Sub SetAllowAlpha(ByVal ctrl As Control, ByVal value As Boolean)
            GetControlFromHashtable(ctrl).AllowAlpha = value
        End Sub
        <Category("Type Validator")> _
        Function GetAllowAlpha(ByVal ctrl As Control) As Boolean
            Return GetControlFromHashtable(ctrl).AllowAlpha
        End Function
        <Category("Type Validator")> _
        Sub SetAllowNumeric(ByVal ctrl As Control, ByVal value As Boolean)
            GetControlFromHashtable(ctrl).AllowNumeric = value
        End Sub
        <Category("Type Validator")> _
        Function GetAllowNumeric(ByVal ctrl As Control) As Boolean
            Return GetControlFromHashtable(ctrl).AllowNumeric
        End Function
        <Category("Type Validator")> _
        Sub SetAllowSpecialChars(ByVal ctrl As Control, ByVal value As CharsAllowSpecialChars)
            GetControlFromHashtable(ctrl).AllowSpecialChars = value
        End Sub
        <Category("Type Validator")> _
        Function GetAllowSpecialChars(ByVal ctrl As Control) As CharsAllowSpecialChars
            Return GetControlFromHashtable(ctrl).AllowSpecialChars
        End Function
        <Category("Type Validator")> _
        Sub SetSpecialCharacters(ByVal ctrl As Control, ByVal value As String)
            GetControlFromHashtable(ctrl).SpecialCharacters = value.ToCharArray
        End Sub
        <Category("Type Validator")> _
        Function GetSpecialCharacters(ByVal ctrl As Control) As String
            Return CType(GetControlFromHashtable(ctrl).SpecialCharacters, String)
        End Function
    #End Region
    #Region "Behavior"
        Private Function GetControlFromHashtable(ByVal ctrl As Control) As KeyValidatorProperties
            If htProvidedProperties.Contains(ctrl) Then
                Return DirectCast(htProvidedProperties(ctrl), KeyValidatorProperties)
            Else
                Dim ProvidedProperties As New KeyValidatorProperties
                'Add A KeyPress Event Handler as the control is added to hash table
                AddHandler ctrl.KeyPress, AddressOf KeyPressHandler
                AddHandler ctrl.TextChanged, AddressOf TextChangedHandler
                htProvidedProperties.Add(ctrl, ProvidedProperties)
                Return ProvidedProperties
            End If
        End Function
       '+++KSG  10/8/2008 1:53:04 PM changed from TextBox to TextBoxBase
       Private Function CleanText(ByVal txtSender As TextBoxBase, ByVal origText As String) As String
          Dim bAlpha As Boolean = GetControlFromHashtable(txtSender).AllowAlpha
          Dim bDigit As Boolean = GetControlFromHashtable(txtSender).AllowNumeric
          Dim bChars As CharsAllowSpecialChars = GetControlFromHashtable(txtSender).AllowSpecialChars
          Dim SpecialCharacters() As Char = GetControlFromHashtable(txtSender).SpecialCharacters
          Dim index As Integer
          Dim sRet As String = ""
          While index < origText.Length
             Dim bCancel As Boolean = True
             Dim character As Char = origText(index)
             If Char.IsControl(character) Then
                bCancel = False
             ElseIf Char.IsLetter(character) AndAlso bAlpha = False Then
                bCancel = True
             ElseIf Char.IsDigit(character) AndAlso bDigit = False Then
                bCancel = True
             ElseIf bChars = CharsAllowSpecialChars.None AndAlso Char.IsLetter(character) = False AndAlso Char.IsDigit(character) = False Then
                bCancel = True
             ElseIf bChars = CharsAllowSpecialChars.NotInList AndAlso Array.IndexOf(SpecialCharacters, character) >= 0 AndAlso Char.IsLetter(character) = False AndAlso Char.IsDigit(character) = False Then
                bCancel = True
             ElseIf bChars = CharsAllowSpecialChars.InList AndAlso Array.IndexOf(SpecialCharacters, character) < 0 AndAlso Char.IsLetter(character) = False AndAlso Char.IsDigit(character) = False Then
                bCancel = True
             Else
                bCancel = False
             End If
             If bCancel = False Then
                sRet &= character
             End If
             index += 1
          End While
          Return sRet
       End Function
        Private Sub TextChangedHandler(ByVal sender As System.Object, ByVal e As System.EventArgs)
          '+++KSG  10/8/2008 1:52:43 PM changed from TextBox to TextBoxBase
          Dim txtSender As TextBoxBase = CType(sender, TextBoxBase)
            Dim sChangedString As String = txtSender.Text
            Dim sCleanString As String = CleanText(txtSender, sChangedString)
            If sChangedString <> sCleanString Then
                txtSender.Text = sCleanString
            End If
        End Sub
        Private Sub KeyPressHandler(ByVal sender As Object, ByVal e As KeyPressEventArgs)
          '+++KSG  10/8/2008 1:51:56 PM changed from TextBox to TextBoxBase
          Dim txtSender As TextBoxBase = CType(sender, TextBoxBase)
            If txtSender.ReadOnly = True Then
                If Char.IsControl(e.KeyChar) Then
                    e.Handled = False
                Else
                    e.Handled = True
                End If
            Else
                If Char.IsControl(e.KeyChar) Then
                    e.Handled = False
                ElseIf Char.IsLetter(e.KeyChar) AndAlso GetControlFromHashtable(txtSender).AllowAlpha = False Then
                    e.Handled = True
                ElseIf Char.IsDigit(e.KeyChar) AndAlso GetControlFromHashtable(txtSender).AllowNumeric = False Then
                    e.Handled = True
                ElseIf GetControlFromHashtable(txtSender).AllowSpecialChars = CharsAllowSpecialChars.None AndAlso Char.IsLetter(e.KeyChar) = False AndAlso Char.IsDigit(e.KeyChar) = False Then
                    e.Handled = True
                ElseIf GetControlFromHashtable(txtSender).AllowSpecialChars = CharsAllowSpecialChars.NotInList AndAlso Array.IndexOf(GetControlFromHashtable(txtSender).SpecialCharacters, e.KeyChar) >= 0 AndAlso Char.IsLetter(e.KeyChar) = False AndAlso Char.IsDigit(e.KeyChar) = False Then
                    e.Handled = True
                ElseIf GetControlFromHashtable(txtSender).AllowSpecialChars = CharsAllowSpecialChars.InList AndAlso Array.IndexOf(GetControlFromHashtable(txtSender).SpecialCharacters, e.KeyChar) < 0 AndAlso Char.IsLetter(e.KeyChar) = False AndAlso Char.IsDigit(e.KeyChar) = False Then
                    e.Handled = True
                Else
                    e.Handled = False
                End If
            End If
        End Sub
    #End Region
    End Class


    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem.

    Saturday, August 10, 2013 11:41 AM
  • Hello,

    I have moved this thread to Visual Basic for better response.

    Best regards,


    Amanda Zhu
    MSDN Community Support | Feedback to us
    Develop and promote your apps in Windows Store
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.

    Monday, August 12, 2013 7:47 AM