Link to home
Start Free TrialLog in
Avatar of RIAS
RIASFlag for United Kingdom of Great Britain and Northern Ireland

asked on

Textbox to not accept characters like '+vb.net

Hello,

How can  I make a textbox to not accept character like '


Cheers
SOLUTION
Avatar of Kyle Abrahams, PMP
Kyle Abrahams, PMP
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Try this out
Dim Not_Accepted As String = "'" ' The charector not required
    Private Sub TextBox1_TextChanged(sender As System.Object, e As System.EventArgs) Handles TextBox1.TextChanged
        Dim xText As String = TextBox1.Text
        Dim xKeys As String
        Dim xSelectionIndex As Integer = TextBox1.SelectionStart
        Dim xChange As Integer
        ' Loop
        For i As Integer = 0 To TextBox1.Text.Length - 1
            xKeys = TextBox1.Text.Substring(i, 1)
            If Not_Accepted.Contains(xKeys) Then
                xText = xText.Replace(xKeys, String.Empty)
                xChange = 1
            End If
        Next
        TextBox1.Text = xText
        TextBox1.Select(xSelectionIndex - xChange, 0)
    End Sub

Open in new window


Note that a character entered at
Not_Accepted

Open in new window

will not be taken by the TextBox
Avatar of RIAS

ASKER

Hello,

Need it for all textboxes nearly 50 to 60 textboxes.
Any way to do it for all in the properties of textbox rather than
Adding a keypress or keydown event for all the textboxes

Thanks
Avatar of RIAS

ASKER

Thanks Saige Sir will try
Avatar of RIAS

ASKER

Any suggestion on  e.KeyCode for character '
Avatar of RIAS

ASKER

Saige Sir,

Is it possible to have a similar function for
 TxtPatientName_KeyPress rather than keydown
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of RIAS

ASKER

Cheers Kyle ! Will try and get back
Avatar of RIAS

ASKER

Kyle,
How to pass arguments in the GenericTextBoxFilter
Avatar of funwithdotnet
funwithdotnet

Yes, I would do it like Kyle.
Understanding that you have already accepted Kyle's answer, there are also other ways to attack this issue:

1.  Using attributes:

Form1.vb -
Imports System.Reflection
Public Class Form1
	Public Sub New()

		' This call is required by the designer.
		InitializeComponent()

		' Add any initialization after the InitializeComponent() call.
		BindKeyDownEvent()
	End Sub

	Private Sub OnKeyDown(sender As Object, e As KeyEventArgs)
		If TypeOf sender Is TextBox Then
			Dim tb = DirectCast(sender, TextBox)
			Dim suppressed = (From [field] In Me.GetType().GetFields(BindingFlags.Instance Or BindingFlags.NonPublic Or BindingFlags.Public Or BindingFlags.Static)
						   Where [field].IsControl() AndAlso [field].GetValue(Me).Equals(tb)
						   From [attribute] As SuppressedKeysAttribute In [field].GetCustomAttributes(GetType(SuppressedKeysAttribute), True)
						   From [key] In [attribute].Keys
						   Select [key])

			If suppressed.Contains(e.KeyCode) Then
				Console.WriteLine("Ah ah ah...  You can't use {0}", e.KeyCode)
				e.SuppressKeyPress = True
				e.Handled = True
			End If
		End If
	End Sub

	Private Sub BindKeyDownEvent()
		Dim bindTo = (From [field] In Me.GetType().GetFields(BindingFlags.Instance Or BindingFlags.NonPublic Or BindingFlags.Public Or BindingFlags.Static)
				    From [attribute] As SuppressedKeysAttribute In [field].GetCustomAttributes(GetType(SuppressedKeysAttribute), True)
				    Where [field].IsControl() AndAlso [attribute] IsNot Nothing
				    Select CType([field].GetValue(Me), Control))
		For Each bind In bindTo
			AddHandler bind.KeyDown, AddressOf OnKeyDown
		Next
	End Sub
End Class

<AttributeUsage(AttributeTargets.All, AllowMultiple:=True)>
Class SuppressedKeysAttribute
	Inherits Attribute
	Public Property Keys() As Keys()
End Class

Module Extensions
	<System.Runtime.CompilerServices.Extension()> _
	Public Function IsControl(member As MemberInfo) As Boolean
		If member Is Nothing Then Return False
		Try
			If TypeOf member Is FieldInfo Then
				Return (DirectCast(member, FieldInfo)).FieldType Is GetType(Control) OrElse (DirectCast(member, FieldInfo)).FieldType.IsSubclassOf(GetType(Control))
			ElseIf TypeOf member Is PropertyInfo Then
				Return (DirectCast(member, PropertyInfo)).PropertyType Is GetType(Control) OrElse (DirectCast(member, PropertyInfo)).PropertyType.IsSubclassOf(GetType(Control))
			Else
				Return False
			End If
		Catch ex As Exception
			Return False
		End Try
	End Function
End Module

Open in new window

Form1.Designer.vb -
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Partial Class Form1
    Inherits System.Windows.Forms.Form

    'Form overrides dispose to clean up the component list.
    <System.Diagnostics.DebuggerNonUserCode()> _
    Protected Overrides Sub Dispose(ByVal disposing As Boolean)
        Try
            If disposing AndAlso components IsNot Nothing Then
                components.Dispose()
            End If
        Finally
            MyBase.Dispose(disposing)
        End Try
    End Sub

    'Required by the Windows Form Designer
    Private components As System.ComponentModel.IContainer

    'NOTE: The following procedure is required by the Windows Form Designer
    'It can be modified using the Windows Form Designer.  
    'Do not modify it using the code editor.
    <System.Diagnostics.DebuggerStepThrough()> _
    Private Sub InitializeComponent()
		Me.Label1 = New System.Windows.Forms.Label()
		Me.TextBox1 = New System.Windows.Forms.TextBox()
		Me.TextBox2 = New System.Windows.Forms.TextBox()
		Me.Label2 = New System.Windows.Forms.Label()
		Me.SuspendLayout()
		'
		'Label1
		'
		Me.Label1.AutoSize = True
		Me.Label1.Location = New System.Drawing.Point(9, 9)
		Me.Label1.Name = "Label1"
		Me.Label1.Size = New System.Drawing.Size(183, 13)
		Me.Label1.TabIndex = 0
		Me.Label1.Text = "This textbox will not accept (a b or c):"
		'
		'TextBox1
		'
		Me.TextBox1.Location = New System.Drawing.Point(12, 25)
		Me.TextBox1.Name = "TextBox1"
		Me.TextBox1.Size = New System.Drawing.Size(260, 20)
		Me.TextBox1.TabIndex = 1
		'
		'TextBox2
		'
		Me.TextBox2.Location = New System.Drawing.Point(12, 64)
		Me.TextBox2.Name = "TextBox2"
		Me.TextBox2.Size = New System.Drawing.Size(260, 20)
		Me.TextBox2.TabIndex = 3
		'
		'Label2
		'
		Me.Label2.AutoSize = True
		Me.Label2.Location = New System.Drawing.Point(9, 48)
		Me.Label2.Name = "Label2"
		Me.Label2.Size = New System.Drawing.Size(180, 13)
		Me.Label2.TabIndex = 2
		Me.Label2.Text = "This textbox will not accept (d e or f):"
		'
		'Form1
		'
		Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!)
		Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
		Me.ClientSize = New System.Drawing.Size(284, 90)
		Me.Controls.Add(Me.TextBox2)
		Me.Controls.Add(Me.Label2)
		Me.Controls.Add(Me.TextBox1)
		Me.Controls.Add(Me.Label1)
		Me.Name = "Form1"
		Me.Text = "Form1"
		Me.ResumeLayout(False)
		Me.PerformLayout()

	End Sub
	Friend WithEvents Label1 As System.Windows.Forms.Label
	<SuppressedKeys(Keys:={Keys.A, Keys.B, Keys.C})> _
	Friend WithEvents TextBox1 As System.Windows.Forms.TextBox
	<SuppressedKeys(Keys:={Keys.D, Keys.E, Keys.F})> _
	Friend WithEvents TextBox2 As System.Windows.Forms.TextBox
	Friend WithEvents Label2 As System.Windows.Forms.Label
End Class

Open in new window


2.  Using a list (or dictionary) set at the form level -

Form1.vb -
Public Class Form1
	ReadOnly suppressed As Dictionary(Of Control, Keys())

	Public Sub New()
		' This call is required by the designer.
		InitializeComponent()

		' Add any initialization after the InitializeComponent() call.
		suppressed = New Dictionary(Of Control, Keys()) From
			{
				{TextBox1, New Keys() {Keys.A, Keys.B, Keys.C}},
				{TextBox2, New Keys() {Keys.D, Keys.E, Keys.F}}
			}

		BindKeyDownEvent()
	End Sub

	Private Sub OnKeyDown(sender As Object, e As KeyEventArgs)
		If TypeOf sender Is TextBox Then
			Dim tb = DirectCast(sender, TextBox)
			If suppressed(tb).Contains(e.KeyCode) Then
				Console.WriteLine("Ah ah ah...  You can't use {0}", e.KeyCode)
				e.SuppressKeyPress = True
				e.Handled = True
			End If
		End If
	End Sub

	Private Sub BindKeyDownEvent()
		For Each pair In suppressed
			AddHandler pair.Key.KeyDown, AddressOf OnKeyDown
		Next
	End Sub
End Class

Open in new window


Form1.Designer.vb -
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Partial Class Form1
    Inherits System.Windows.Forms.Form

    'Form overrides dispose to clean up the component list.
    <System.Diagnostics.DebuggerNonUserCode()> _
    Protected Overrides Sub Dispose(ByVal disposing As Boolean)
        Try
            If disposing AndAlso components IsNot Nothing Then
                components.Dispose()
            End If
        Finally
            MyBase.Dispose(disposing)
        End Try
    End Sub

    'Required by the Windows Form Designer
    Private components As System.ComponentModel.IContainer

    'NOTE: The following procedure is required by the Windows Form Designer
    'It can be modified using the Windows Form Designer.  
    'Do not modify it using the code editor.
    <System.Diagnostics.DebuggerStepThrough()> _
    Private Sub InitializeComponent()
		Me.Label1 = New System.Windows.Forms.Label()
		Me.TextBox1 = New System.Windows.Forms.TextBox()
		Me.TextBox2 = New System.Windows.Forms.TextBox()
		Me.Label2 = New System.Windows.Forms.Label()
		Me.SuspendLayout()
		'
		'Label1
		'
		Me.Label1.AutoSize = True
		Me.Label1.Location = New System.Drawing.Point(9, 9)
		Me.Label1.Name = "Label1"
		Me.Label1.Size = New System.Drawing.Size(183, 13)
		Me.Label1.TabIndex = 0
		Me.Label1.Text = "This textbox will not accept (a b or c):"
		'
		'TextBox1
		'
		Me.TextBox1.Location = New System.Drawing.Point(12, 25)
		Me.TextBox1.Name = "TextBox1"
		Me.TextBox1.Size = New System.Drawing.Size(260, 20)
		Me.TextBox1.TabIndex = 1
		'
		'TextBox2
		'
		Me.TextBox2.Location = New System.Drawing.Point(12, 64)
		Me.TextBox2.Name = "TextBox2"
		Me.TextBox2.Size = New System.Drawing.Size(260, 20)
		Me.TextBox2.TabIndex = 3
		'
		'Label2
		'
		Me.Label2.AutoSize = True
		Me.Label2.Location = New System.Drawing.Point(9, 48)
		Me.Label2.Name = "Label2"
		Me.Label2.Size = New System.Drawing.Size(180, 13)
		Me.Label2.TabIndex = 2
		Me.Label2.Text = "This textbox will not accept (d e or f):"
		'
		'Form1
		'
		Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!)
		Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
		Me.ClientSize = New System.Drawing.Size(284, 90)
		Me.Controls.Add(Me.TextBox2)
		Me.Controls.Add(Me.Label2)
		Me.Controls.Add(Me.TextBox1)
		Me.Controls.Add(Me.Label1)
		Me.Name = "Form1"
		Me.Text = "Form1"
		Me.ResumeLayout(False)
		Me.PerformLayout()

	End Sub
	Friend WithEvents Label1 As System.Windows.Forms.Label
	Friend WithEvents TextBox1 As System.Windows.Forms.TextBox
	Friend WithEvents TextBox2 As System.Windows.Forms.TextBox
	Friend WithEvents Label2 As System.Windows.Forms.Label
End Class

Open in new window


3.  Creating your own control and overriding the keydown event -

Form1.vb -
Public Class Form1
	Public Sub New()
		' This call is required by the designer.
		InitializeComponent()

		' Add any initialization after the InitializeComponent() call.
		TextBox1.SuppressedKeys.AddRange({Keys.A, Keys.B, Keys.C})
		TextBox2.SuppressedKeys.AddRange({Keys.D, Keys.E, Keys.F})
	End Sub
End Class

Class SuppressedKeysTextBox
	Inherits TextBox
	Public Property SuppressedKeys() As New List(Of Keys)

	Protected Overrides Sub OnKeyDown(e As KeyEventArgs)
		If SuppressedKeys.Contains(e.KeyCode) Then
			Console.WriteLine("Ah ah ah...  You can't use {0}", e.KeyCode)
			e.SuppressKeyPress = True
			e.Handled = True
		End If
		MyBase.OnKeyDown(e)
	End Sub
End Class

Open in new window

Form1.Designer.vb -
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Partial Class Form1
	Inherits System.Windows.Forms.Form

	'Form overrides dispose to clean up the component list.
	<System.Diagnostics.DebuggerNonUserCode()> _
	Protected Overrides Sub Dispose(ByVal disposing As Boolean)
		Try
			If disposing AndAlso components IsNot Nothing Then
				components.Dispose()
			End If
		Finally
			MyBase.Dispose(disposing)
		End Try
	End Sub

	'Required by the Windows Form Designer
	Private components As System.ComponentModel.IContainer

	'NOTE: The following procedure is required by the Windows Form Designer
	'It can be modified using the Windows Form Designer.  
	'Do not modify it using the code editor.
	<System.Diagnostics.DebuggerStepThrough()> _
	Private Sub InitializeComponent()
		Me.Label1 = New System.Windows.Forms.Label()
		Me.TextBox1 = New SuppressedKeysTextBox()
		Me.TextBox2 = New SuppressedKeysTextBox()
		Me.Label2 = New System.Windows.Forms.Label()
		Me.SuspendLayout()
		'
		'Label1
		'
		Me.Label1.AutoSize = True
		Me.Label1.Location = New System.Drawing.Point(9, 9)
		Me.Label1.Name = "Label1"
		Me.Label1.Size = New System.Drawing.Size(183, 13)
		Me.Label1.TabIndex = 0
		Me.Label1.Text = "This textbox will not accept (a b or c):"
		'
		'TextBox1
		'
		Me.TextBox1.Location = New System.Drawing.Point(12, 25)
		Me.TextBox1.Name = "TextBox1"
		Me.TextBox1.Size = New System.Drawing.Size(260, 20)
		Me.TextBox1.TabIndex = 1
		'
		'TextBox2
		'
		Me.TextBox2.Location = New System.Drawing.Point(12, 64)
		Me.TextBox2.Name = "TextBox2"
		Me.TextBox2.Size = New System.Drawing.Size(260, 20)
		Me.TextBox2.TabIndex = 3
		'
		'Label2
		'
		Me.Label2.AutoSize = True
		Me.Label2.Location = New System.Drawing.Point(9, 48)
		Me.Label2.Name = "Label2"
		Me.Label2.Size = New System.Drawing.Size(180, 13)
		Me.Label2.TabIndex = 2
		Me.Label2.Text = "This textbox will not accept (d e or f):"
		'
		'Form1
		'
		Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!)
		Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
		Me.ClientSize = New System.Drawing.Size(284, 90)
		Me.Controls.Add(Me.TextBox2)
		Me.Controls.Add(Me.Label2)
		Me.Controls.Add(Me.TextBox1)
		Me.Controls.Add(Me.Label1)
		Me.Name = "Form1"
		Me.Text = "Form1"
		Me.ResumeLayout(False)
		Me.PerformLayout()

	End Sub
	Friend WithEvents Label1 As System.Windows.Forms.Label
	Friend WithEvents TextBox1 As SuppressedKeysTextBox
	Friend WithEvents TextBox2 As SuppressedKeysTextBox
	Friend WithEvents Label2 As System.Windows.Forms.Label
End Class

Open in new window


All three of the preceeding implementations produce the exact same results.

-saige-
Avatar of RIAS

ASKER

Thank you Saige Sir!