Textbox validation for alphabetical and alphanumeric textbox with "." - vb.net

This is what i am using but i want to include "." dot also as an input in the textbox
If Char.IsLetter(e.KeyChar) = False Then
If e.KeyChar = CChar(ChrW(Keys.Back)) or e.KeyChar = CChar(ChrW(Keys.Space)) Then
e.Handled = False
Else
e.Handled = True
End If
End If
and
If Char.IsLetterOrDigit(e.KeyChar) = False Then
If e.KeyChar = CChar(ChrW(Keys.Back)) or e.KeyChar = CChar(ChrW(Keys.Space)) Then
e.Handled = False
Else
e.Handled = True
End If
End If

To include a period in the list of valid characters, use an OrElse term to test for multiple conditions. Note that "." is a String, different to "."c which is a Char.
If Not (Char.IsLetterOrDigit(e.KeyChar) OrElse e.KeyChar = "."c) Then
If e.KeyChar = CChar(ChrW(Keys.Back)) or e.KeyChar = CChar(ChrW(Keys.Space)) Then
e.Handled = False
Else
e.Handled = True
End If
End If

You could just use ASCII code
If Asc(C$(F1)) > 122 Or Asc(C$(F1)) < 97 And Asc(C$(F1)) > 90 Or Asc(C$(F1)) < 65 And Asc(C$(F1)) > 57 Or Asc(C$(F1)) < 48 Then
Label9.Text = C$(F1) + " is an invalid Charater!"
End If
For a single character you can just do Or variable =".". ASCII works when you want a range.
The code snippet is from Numeric Base conversion program check for invalid charters in a number, which will convert any base from 2 to 36. And, with minor tweaking will work in any form of BASIC including Applesoft (tweak no end if, and all on one line, label9.text becomes a text varible) which can also be done in VB.

You can use my control:
''' <summary>
''' By Amen Ayach
''' Use RoundNumber property to set how many decimal after "."
''' example: RoundNumber = 3 so if you write 654.4444 so onlostFocus you'll see 654.444
''' </summary>
''' <remarks></remarks>
Public Class TBRound
Inherits TextBox
Dim Enterly As Boolean = True
Private _RoundNumber As Integer = 0
Public Property RoundNumber() As Integer
Get
Return _RoundNumber
End Get
Set(ByVal value As Integer)
_RoundNumber = value
End Set
End Property
Public Overrides Property Text() As String
Get
Return MyBase.Text
End Get
Set(ByVal value As String)
MyBase.Text = value
End Set
End Property
Public Function format_Number(ByVal nb As String, ByVal isDivided As Boolean, ByVal NumberAfterComma As Integer) As String
Dim str As String = ""
Try
Dim fromatString As String = ""
Dim nbs As String = "."
For i As Integer = 0 To NumberAfterComma - 1
nbs += "0"
Next
If isDivided Then
str = "#,###"
Else
str = "#"
End If
str += nbs
str = Format(Val(Decimal.Parse(nb.ToString())), str)
Catch
End Try
Return str
End Function
Private Sub TBRound_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles Me.KeyPress
Dim allow As String = "0123456789." + ChrW(Keys.Back) + ChrW(Keys.Delete)
If Not allow.Contains(e.KeyChar) Then
e.Handled = True
End If
End Sub
Private Sub TBRound_LostFocus(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.LostFocus, Me.Validated
Try
If Not Decimal.TryParse(MyBase.Text, New Decimal) Then
MyBase.Text = "0"
Else
ValDateMe()
End If
Catch
End Try
End Sub
Private Sub ValDateMe()
Try
Dim value = MyBase.Text
If Decimal.TryParse(MyBase.Text, New Decimal) Then
If MyBase.Text <> format_Number(MyBase.Text, False, RoundNumber) Then
MyBase.Text = format_Number(MyBase.Text, False, RoundNumber)
End If
Else
Enterly = False
MyBase.Text = "0"
Enterly = True
End If
Catch
End Try
End Sub
End Class

You can use the following function:
Private Function StripInput(sender As String) As String
If sender <> String.Empty Then
Dim lastChr As String = sender(sender.Length - 1)
Dim stripList As String = "`¬!""£$%^&*()_+-=}{[]}~##'':?/>.<,|\;"
If stripList.Contains(lastChr) Then
Return sender.Substring(0, sender.Length - 1)
Else
Return sender
End If
Else
Return sender
End If
End Function
and call it from the TextChanged handler of the text box with :
sender.text = StripInput(sender.text)
sender.SelectionStart = sender.Text.Length + 1
And if you want to include any character, simply remove it from the strip list.

Related

Error adding control from toolbox to windows form

i have class inherited from textbox , and when i try to add the control from the toolbox i have this error in the picture.
this is class inherited from textbox control ,using listbox control to choose from auto complete list
Public Structure Account
Dim Name As String
Dim Number As String
Public Sub New(Namee As String, Num As String)
Name = Namee
Number = Num
End Sub
Public Overrides Function ToString() As String
Return Name
End Function
End Structure
Public Class AutoCompleteTextBox
Inherits TextBox
Private ACL As List(Of Account), CACL As List(Of Account)
Private CaseSensitive As Boolean
Private MinChar As Integer
Private LS As ListBox
Private OLDText As String
Private PN As Panel
Public Sub New()
MyBase.New
MinTypedCharacters = 2
CaseSesitivity = False
ACL = New List(Of Account)
LS = New ListBox
LS.Name = "SeggestionListBox"
LS.Font = Font
LS.Visible = True
PN = New Panel
PN.Visible = False
PN.Font = Font
PN.AutoSizeMode = AutoSizeMode.GrowAndShrink
PN.ClientSize = New Size(1, 1)
PN.Name = "SeggestionPanel"
PN.Padding = New Padding(0, 0, 0, 0)
PN.Margin = New Padding(0, 0, 0, 0)
PN.BackColor = Color.Transparent
PN.ForeColor = Color.Transparent
PN.PerformLayout()
If Not PN.Controls.Contains(LS) Then
PN.Controls.Add(LS)
End If
LS.Dock = DockStyle.Fill
LS.SelectionMode = SelectionMode.One
AddHandler LS.KeyDown, AddressOf LS_KeyDown
AddHandler LS.MouseClick, AddressOf LS_MouseClick
AddHandler LS.MouseDoubleClick, AddressOf LS_MouseDoubleClick
CACL = New List(Of Account)
LS.DataSource = CACL
OLDText = Text
End Sub
#Region "Properties"
Public Property AutoCompleteList As List(Of Account)
Get
Return ACL
End Get
Set(value As List(Of Account))
ACL.Clear()
ACL = value
End Set
End Property
Public Property CaseSesitivity As Boolean
Get
Return CaseSensitive
End Get
Set(value As Boolean)
CaseSensitive = value
End Set
End Property
Public Property MinTypedCharacters As Integer
Get
Return MinChar
End Get
Set(value As Integer)
MinChar = value
End Set
End Property
Public Property SelectedIndex As Integer
Get
Return LS.SelectedIndex
End Get
Set(value As Integer)
If LS.Items.Count <> 0 Then
LS.SelectedIndex = value
End If
End Set
End Property
Private ReadOnly Property ParentForm As Form
Get
Return Me.Parent.FindForm
End Get
End Property
#End Region
Public Sub HideSuggestionListBox()
If Not ParentForm Is Nothing Then
PN.Hide()
If ParentForm.Controls.Contains(PN) Then
ParentForm.Controls.Remove(PN)
End If
End If
End Sub
Private Function SelectItem() As Boolean
If LS.Items.Count > 0 AndAlso LS.SelectedIndex > -1 Then
Text = LS.SelectedItem.ToString
HideSuggestionListBox()
End If
Return True
End Function
Protected Overrides Sub OnKeyDown(e As KeyEventArgs)
If e.KeyCode = Keys.Up Then
MoveSelection(SelectedIndex - 1)
e.Handled = True
ElseIf e.KeyCode = Keys.Down Then
MoveSelection(SelectedIndex + 1)
e.Handled = True
ElseIf e.KeyCode = Keys.PageUp Then
MoveSelection(SelectedIndex - 10)
e.Handled = True
ElseIf e.KeyCode = Keys.PageDown Then
MoveSelection(SelectedIndex + 10)
e.Handled = True
ElseIf e.KeyCode = Keys.Enter Then
SelectItem()
e.Handled = True
Else
MyBase.OnKeyDown(e)
End If
End Sub
Protected Overrides Sub OnLostFocus(e As EventArgs)
If Not PN.ContainsFocus Then
MyBase.OnLostFocus(e)
If Not CheckItem(Text) Then
Text = ""
End If
HideSuggestionListBox()
End If
End Sub
Protected Overrides Sub OnTextChanged(e As EventArgs)
If Not DesignMode Then
ShowSuggests()
End If
MyBase.OnTextChanged(e)
OLDText = Text
End Sub
Private Sub LS_KeyDown(ByVal sender As Object, ByVal e As KeyEventArgs)
If (e.KeyCode = Keys.Enter) Then
Me.SelectItem()
e.Handled = True
End If
End Sub
Private Sub LS_MouseClick(ByVal sender As Object, ByVal e As MouseEventArgs)
' select the current item
Me.SelectItem()
MsgBox(LS.SelectedItem.number)
End Sub
Private Sub LS_MouseDoubleClick(ByVal sender As Object, ByVal e As MouseEventArgs)
Me.SelectItem()
End Sub
Private Function CheckItem(ItemSTR As String) As Boolean
For Each STR As Account In ACL
If ItemSTR.ToLower = STR.ToString.ToLower Then
Return True
Exit Function
End If
Next
Return False
End Function
Private Sub MoveSelection(Index As Integer)
If Index <= -1 Then
SelectedIndex = 0
ElseIf Index > (LS.Items.Count - 1) Then
SelectedIndex = LS.Items.Count - 1
Else
SelectedIndex = Index
End If
End Sub
Private Sub ShowSuggests()
If Text.Length >= MinTypedCharacters Then
PN.SuspendLayout()
If Text.Length > 0 AndAlso OLDText = Text.Substring(0, Text.Length - 1) Then
UpdateCurrentAutoCompleteList()
ElseIf OLDText.Length > 0 AndAlso Text = OLDText.Substring(0, OLDText.Length - 1) Then
UpdateCurrentAutoCompleteList()
Else
UpdateCurrentAutoCompleteList()
End If
If Not CACL Is Nothing AndAlso CACL.Count > 0 Then
PN.Show()
PN.BringToFront()
Focus()
Else
HideSuggestionListBox()
End If
PN.ResumeLayout()
Else
HideSuggestionListBox()
End If
End Sub
Private Sub UpdateCurrentAutoCompleteList()
CACL.Clear()
For Each STR As Account In ACL
If CaseSesitivity = True Then
If STR.ToString.IndexOf(Text) > -1 Then
CACL.Add(STR)
End If
Else
If STR.ToString.ToLower.IndexOf(Text.ToLower) > -1 Then
CACL.Add(STR)
End If
End If
Next
If CACL.Count > 0 Then
UpdateListBoxItems()
Else
HideSuggestionListBox()
End If
End Sub
Private Sub UpdateListBoxItems()
If Not ParentForm Is Nothing Then
PN.Width = Width
'PN.Height = ParentForm.ClientSize.Height - Height - Location.Y
Dim F As Integer = ParentForm.ClientSize.Height - Height - Location.Y
Dim Ten As Integer = Font.Height * 10
Dim CUr As Integer = Font.Height * (CACL.Count + 1)
If F < CUr Then
PN.Height = F
ElseIf CUr < Ten Then
PN.Height = CUr
ElseIf Ten < F Then
PN.Height = Ten
Else
PN.Height = F
End If
'PN.Height = Font.Height * 10
PN.Location = Location + New Size(0, Height)
If Not ParentForm.Controls.Contains(PN) Then
ParentForm.Controls.Add(PN)
End If
CType(LS.BindingContext(CACL), CurrencyManager).Refresh()
End If
End Sub
End Class
firstly i used list(of string) before using the structure account .
the problem appears after using the structure
Any Idea about this error ?
**** additional picture show another problem after substitutes the structure with class and adds attribute.
***** changed the Structure to class
<Serializable> Public Class Account
Private Nam As String
Private Numbe As String
Public Sub New(Namee As String, Num As String)
Name = Namee
Number = Num
End Sub
Public Property Name As String
Get
Return Nam
End Get
Set(value As String)
Nam = value
End Set
End Property
Public Property Number As String
Get
Return Numbe
End Get
Set(value As String)
Numbe = value
End Set
End Property
Public Overrides Function ToString() As String
Return Name
End Function
End Class
Problem Resolved*
i will share the solve with you.
all the problem is coming from the line
ACL = New List(Of Account)
and the line
CACL = New List(Of Account)
because it declare new list(of account) in design time.
i solved the problem by deleting the both of line and modified the property (AutoCompleteList) to be like that.
Public WriteOnly Property AutoCompleteList As List(Of Account)
Set(value As List(Of Account))
ACL = value
CACL = New List(Of Account)
End Set
End Property
and the final code will be like that:-
the structure:
Public Structure Account
Public Name As String
Public Number As String
Public Sub New(Namee As String, Num As String)
Name = Namee
Number = Num
End Sub
Public Overrides Function ToString() As String
Return Name
End Function
End Structure
the class:
Public Class AutoCompleteTextBox
Inherits TextBox
Private ACL As List(Of Account), CACL As List(Of Account)
Private CaseSensitive As Boolean
Private MinChar As Integer
Private LS As ListBox
Private OLDText As String
Private PN As Panel
Public Sub New()
MyBase.New
MinTypedCharacters = 2
CaseSesitivity = False
LS = New ListBox
LS.Name = "SeggestionListBox"
LS.Font = Font
LS.Visible = True
PN = New Panel
PN.Visible = False
PN.Font = Font
PN.AutoSizeMode = AutoSizeMode.GrowAndShrink
PN.ClientSize = New Size(1, 1)
PN.Name = "SeggestionPanel"
PN.Padding = New Padding(0, 0, 0, 0)
PN.Margin = New Padding(0, 0, 0, 0)
PN.BackColor = Color.Transparent
PN.ForeColor = Color.Transparent
PN.PerformLayout()
If Not PN.Controls.Contains(LS) Then
PN.Controls.Add(LS)
End If
LS.Dock = DockStyle.Fill
LS.SelectionMode = SelectionMode.One
AddHandler LS.KeyDown, AddressOf LS_KeyDown
AddHandler LS.MouseClick, AddressOf LS_MouseClick
AddHandler LS.MouseDoubleClick, AddressOf LS_MouseDoubleClick
LS.DataSource = CACL
OLDText = Text
End Sub
Public WriteOnly Property AutoCompleteList As List(Of Account)
Set(value As List(Of Account))
'ACL.Clear()
ACL = value
CACL = New List(Of Account)
End Set
End Property
Public Property CaseSesitivity As Boolean
Get
Return CaseSensitive
End Get
Set(value As Boolean)
CaseSensitive = value
End Set
End Property
Public Property MinTypedCharacters As Integer
Get
Return MinChar
End Get
Set(value As Integer)
MinChar = value
End Set
End Property
Public Property SelectedIndex As Integer
Get
Return LS.SelectedIndex
End Get
Set(value As Integer)
If LS.Items.Count <> 0 Then
LS.SelectedIndex = value
End If
End Set
End Property
Private ReadOnly Property ParentForm As Form
Get
Return Me.Parent.FindForm
End Get
End Property
Public Sub HideSuggestionListBox()
If Not ParentForm Is Nothing Then
PN.Hide()
If ParentForm.Controls.Contains(PN) Then
ParentForm.Controls.Remove(PN)
End If
End If
End Sub
Private Function SelectItem() As Boolean
If LS.Items.Count > 0 AndAlso LS.SelectedIndex > -1 Then
Text = LS.SelectedItem.ToString
MsgBox(LS.SelectedItem.number)
HideSuggestionListBox()
End If
Return True
End Function
Protected Overrides Sub OnKeyDown(e As KeyEventArgs)
If e.KeyCode = Keys.Up Then
MoveSelection(SelectedIndex - 1)
e.Handled = True
ElseIf e.KeyCode = Keys.Down Then
MoveSelection(SelectedIndex + 1)
e.Handled = True
ElseIf e.KeyCode = Keys.PageUp Then
MoveSelection(SelectedIndex - 10)
e.Handled = True
ElseIf e.KeyCode = Keys.PageDown Then
MoveSelection(SelectedIndex + 10)
e.Handled = True
ElseIf e.KeyCode = Keys.Enter Then
SelectItem()
e.Handled = True
Else
MyBase.OnKeyDown(e)
End If
End Sub
Protected Overrides Sub OnLostFocus(e As EventArgs)
If Not PN.ContainsFocus Then
MyBase.OnLostFocus(e)
If Not CheckItem(Text) Then
Text = ""
End If
HideSuggestionListBox()
End If
End Sub
Protected Overrides Sub OnTextChanged(e As EventArgs)
If Not DesignMode Then
ShowSuggests()
End If
MyBase.OnTextChanged(e)
OLDText = Text
End Sub
Private Sub LS_KeyDown(ByVal sender As Object, ByVal e As KeyEventArgs)
If (e.KeyCode = Keys.Enter) Then
Me.SelectItem()
e.Handled = True
End If
End Sub
Private Sub LS_MouseClick(ByVal sender As Object, ByVal e As MouseEventArgs)
' select the current item
Me.SelectItem()
MsgBox(LS.SelectedItem.number)
End Sub
Private Sub LS_MouseDoubleClick(ByVal sender As Object, ByVal e As MouseEventArgs)
Me.SelectItem()
End Sub
Private Function CheckItem(ItemSTR As String) As Boolean
For Each STR As Account In ACL
If ItemSTR.ToLower = STR.ToString.ToLower Then
Return True
Exit Function
End If
Next
Return False
End Function
Private Sub MoveSelection(Index As Integer)
If Index <= -1 Then
SelectedIndex = 0
ElseIf Index > (LS.Items.Count - 1) Then
SelectedIndex = LS.Items.Count - 1
Else
SelectedIndex = Index
End If
End Sub
Private Sub ShowSuggests()
If Text.Length >= MinTypedCharacters Then
PN.SuspendLayout()
If Text.Length > 0 AndAlso OLDText = Text.Substring(0, Text.Length - 1) Then
UpdateCurrentAutoCompleteList()
ElseIf OLDText.Length > 0 AndAlso Text = OLDText.Substring(0, OLDText.Length - 1) Then
UpdateCurrentAutoCompleteList()
Else
UpdateCurrentAutoCompleteList()
End If
If Not CACL Is Nothing AndAlso CACL.Count > 0 Then
PN.Show()
PN.BringToFront()
Focus()
Else
HideSuggestionListBox()
End If
PN.ResumeLayout()
Else
HideSuggestionListBox()
End If
End Sub
Private Sub UpdateCurrentAutoCompleteList()
CACL.Clear()
For Each STR As Account In ACL
If CaseSesitivity = True Then
If STR.ToString.IndexOf(Text) > -1 Then
CACL.Add(STR)
End If
Else
If STR.ToString.ToLower.IndexOf(Text.ToLower) > -1 Then
CACL.Add(STR)
End If
End If
Next
If CACL.Count > 0 Then
UpdateListBoxItems()
Else
HideSuggestionListBox()
End If
End Sub
Sub Fill()
For Each A As Account In CACL
LS.Items.Add(A)
Next
End Sub
Private Sub UpdateListBoxItems()
If Not ParentForm Is Nothing Then
PN.Width = Width
'PN.Height = ParentForm.ClientSize.Height - Height - Location.Y
Dim F As Integer = ParentForm.ClientSize.Height - Height - Location.Y
Dim Ten As Integer = Font.Height * 10
Dim CUr As Integer = Font.Height * (CACL.Count + 1)
If F < CUr Then
PN.Height = F
ElseIf CUr < Ten Then
PN.Height = CUr
ElseIf Ten < F Then
PN.Height = Ten
Else
PN.Height = F
End If
'PN.Height = Font.Height * 10
PN.Location = Location + New Size(0, Height)
If Not ParentForm.Controls.Contains(PN) Then
ParentForm.Controls.Add(PN)
End If
Fill()
End If
End Sub
End Class
thank you all.

VB.NET validate the form to check if empty fields or errors exists

So far I have written code to remain Save&Update buttons disabled until user fills all required fields(Textboxes & Comboboxes) in Groupbox, but I also want the Save&Update buttons to remain disabled until user has addressed all errors available in the form e.g Book_Name should not go beyond 50 characters!
I would really appreciate if someone help me in this!
Below is the code that I tried to do so what I have mentioned above but somehow it is not working:
Private Sub ValidateInputs(ByVal Sender As Object, ByVal e As EventArgs)
Dim ctrl As Control
Dim strErrorList As String
strErrorList = ""
For Each ctrl In Me.Controls
If Len(ErrorProvider1.GetError(ctrl)) > 0 Then
strErrorList += ErrorProvider1.GetError(ctrl) & ChrW(10) &
ChrW(13)
End If
Next
If Len(strErrorList) = 0 Then
' Process stuff if no errors
btnsave.Enabled = Not GroupBox1.Controls.OfType(Of TextBox).Any(Function(t) t.Text = String.Empty) And _
Not (cboStaff_id.Text = String.Empty OrElse cboPub_id.Text = String.Empty OrElse cboSub_Code.Text = String.Empty _
OrElse DateTimePicker1.Text = " ")
btnSaveUpdate.Enabled = Not GroupBox1.Controls.OfType(Of ComboBox).Any(Function(cbo) cbo.Text = String.Empty) And _
Not (txtbook_name.Text = String.Empty OrElse txtauthor.Text = String.Empty OrElse txtprice.Text = String.Empty _
OrElse txtrack_no.Text = String.Empty OrElse TxtNo_of_Books.Text = String.Empty OrElse txtvol_no.Text = String.Empty OrElse DateTimePicker1.Text = " ")
btndelete.Enabled = Not (cboISBN.Text = String.Empty)
Else
btnsave.Enabled = False
btnSaveUpdate.Enabled = False
MessageBox.Show(strErrorList, "List Of Errors")
End If
End Sub
Use Error Providers Or Create your own error provider that does the task required for you and for the ISBN textBox say put the MaxLength=13 it will do the task without any error providers or validators, For phone number of email use masked text box, or handle the text change event of the textbox if you want to accept only numbers in that textbox
Since I asked the question 4 days ago and no one provided an answer to solve my problem, I researched & rechecked my code and found solution for my problem!
So I am gonna explain each point to clarify what I have done.
'Below disables numeric entry; only characters and spaces allowed with the help of ASCII values
Private Sub txtbook_name_KeyPress(sender As Object, e As KeyPressEventArgs) Handles txtbook_name.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) _
Or (Asc(e.KeyChar) = 32)) Then
e.KeyChar = ChrW(0)
e.Handled = True
End If
End If
End Sub
'Bellow function return only true if input matches Regex pattern in other cases false
Private Function ValidBook_name(ByVal book_name As String, ByRef errorMessage As String) As Boolean
Dim regex As New System.Text.RegularExpressions.Regex("^[a-zA-Z ]{1,50}$")
' Confirm there is text in the control.
If txtbook_name.Text.Length = 0 Then
errorMessage = "Book Name is required"
Return False
End If
If txtbook_name.Text.Length > 50 Then
errorMessage = "Book Name can not be more than 50"
Return False
End If
'Confirm that book name is in character not number
If (regex.IsMatch(Trim(txtbook_name.Text))) Then
errorMessage = ""
Return True
End If
errorMessage = "A valid Book Name is required" + ControlChars.Cr
Return False
End Function
'Check whether input entered is valid or not; if not return cursor to control
Private Sub txtbook_name_Validating(ByVal sender As Object, _
ByVal e As System.ComponentModel.CancelEventArgs) Handles txtbook_name.Validating
Dim errorMsg As String
Try
If Not ValidBook_name(txtbook_name.Text, errorMsg) Then
' Cancel the event and select the text to be corrected by the user.
e.Cancel = True
txtbook_name.Select(0, txtbook_name.Text.Length)
' Set the ErrorProvider error with the text to display.
Me.ErrorProvider1.SetError(txtbook_name, errorMsg)
End If
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
Private Sub txtbook_name_Validated(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles txtbook_name.Validated
' If all conditions have been met, clear the error provider of errors.
Try
ErrorProvider1.SetError(txtbook_name, "")
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
Hope this helps...

How to check if text box max length has been exceeded?

My problem:
I'm limiting a text box to 8 characters and showing a tooltip when it's exceeded (>8) rather than reached (=8). Using the .Maxlength function prevents the user from ever exceeding 8 characters so my >8 function is never fulfilled.
If I forgo the .Maxlength function and instead use .Substring to limit the input, my >8 function is fulfilled however the behavior differs from .Substring (the last rather than first 8 inputs are kept and I lose the alert sound).
It would a lot cleaner to be able to check for whenever .Maxlength is exceeded without affecting the first 8 inputs.
To reproduce:
In Visual Studio, in design mode, drag a text box and tooltip onto a fresh form.
Use the following as is:
Code:
Public Class Form1
Private Sub Textbox1_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged
TextBox1.MaxLength = 8
If (Not IsNumeric(TextBox1.Text) And TextBox1.Text.Length > 0) Then
If ToolTip1.GetToolTip(TextBox1) = "" Then
ToolTip1.ToolTipTitle = "Input must be numeric!"
ToolTip1.Active = True
ToolTip1.IsBalloon = True
ToolTip1.ToolTipIcon = ToolTipIcon.Warning
ToolTip1.Show(vbNewLine, TextBox1, 45, -40)
End If
ElseIf TextBox1.Text.Length > 8 Then
'TextBox1.Text = TextBox1.Text.Substring(0, 8)
ToolTip1.IsBalloon = True
ToolTip1.ToolTipTitle = "8 character maximum!"
ToolTip1.Active = True
ToolTip1.ToolTipIcon = ToolTipIcon.Warning
ToolTip1.Show(vbNewLine, TextBox1, 45, -40)
Else
ToolTip1.Active = False
ToolTip1.Hide(TextBox1)
End If
End Sub
End Class
When you replace the text, it resets the caret, so move it back into place at the end:
TextBox1.Text = TextBox1.Text.Substring(0, 8)
TextBox1.Select(TextBox1.TextLength, 0)
It is better to supress the key if it is invalid:
Private Sub TextBox1_KeyPress(sender As System.Object, e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
Dim str As String
str = TextBox1.Text
str = str.Insert(TextBox1.SelectionStart, CStr(e.KeyChar))
If e.KeyChar = ChrW(Keys.Back) Then
HideToolTip()
ElseIf str.Length > 8 Then
ShowToolTip("8 character maximum!")
e.Handled = True
ElseIf Not IsNumeric(str) Then
ShowToolTip("Input must be numeric!")
e.Handled = True
Else
HideToolTip()
End If
End Sub
Private Sub HideToolTip()
If ToolTip1.GetToolTip(TextBox1) <> "" Then
ToolTip1.Active = False
ToolTip1.Hide(TextBox1)
End If
End Sub
Private Sub ShowToolTip(ByVal str As String)
'always check if tooltip is visible, to avoid inversion
If ToolTip1.GetToolTip(TextBox1) = "" Then
ToolTip1.ToolTipTitle = str
ToolTip1.Active = True
ToolTip1.IsBalloon = True
ToolTip1.ToolTipIcon = ToolTipIcon.Warning
ToolTip1.Show(vbNewLine, TextBox1, 45, -40, 1000)
End If
End Sub
EDIT
There is a minor "bug" in IsNumeric() function as it allows numeric with spaces and multiple "."
8..888 'is numeric
.9999 'is numeric
To solve everything:
Private Sub TextBox1_KeyPress(sender As System.Object, e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
Dim str As String = "0123456789."
If e.KeyChar = ChrW(Keys.Back) Then
HideToolTip()
ElseIf TextBox1.Text.Length = 8 Then
ShowToolTip("8 character maximum!")
e.Handled = True
ElseIf e.KeyChar = "." And (TextBox1.Text.Contains(".") Or TextBox1.SelectionStart = 0) Then 'supress a second "." or a first one
ShowToolTip("Input must be numeric!")
e.Handled = True
ElseIf Not str.Contains(CStr(e.KeyChar)) Then
ShowToolTip("Input must be numeric!")
e.Handled = True
Else
HideToolTip()
End If
End Sub
Add this after the substring call
TextBox1.SelectionStart = 8

Return false if char is repeated

I'm coding in a DataGridView, and validating if the cell has a format of numbers and comma only, the cell is for document pages,
sample format that would return true, or accept: 1,2 or 1,2,5 BUT NOT 1,,2 or 1,,,6,2
I have made a function for that, and it works fine, BUT I'm not comfortable using my code, I hope there is a better code than I have.
Please correct my code for better.
Thanks.
Private Function isCELLPageNumb(ByRef valyo As String, ByVal origMaxPage As String) As Boolean
If valyo = "0" Or valyo = "," Then
valyo = origMaxPage
Return False
End If
Dim allowedChars As String = "0123456789,"
For i As Integer = (valyo.Length - 1) To 0 Step -1
If allowedChars.IndexOf(valyo(i)) = -1 Then
valyo = origMaxPage
Return False
End If
Try
If valyo(i) = "," Then
If valyo(i + 1) = "," Then
valyo = origMaxPage
Return False
End If
End If
Catch ex As Exception
valyo = origMaxPage
Return False
End Try
''I THINK I HAVE TO SEE IF THE COMMA NEXT NUMBER IS GREATER THAN THE MAXPAGE
''If valyo(i)>origMaxPage then
''End If
Next
Return True
End Function
Edited the origMaxPage
Private Function isCELLPageNumb(ByRef valyo As String, ByVal origMaxPage As String) As Boolean
If valyo = "0" Or valyo = "," Then
valyo = origMaxPage
Return False
End If
Dim allowedChars As String = "0123456789,"
For i As Integer = (valyo.Length - 1) To 0 Step -1
''IF ALLOWED CHARACTERS NOT IN THE INDEX
If allowedChars.IndexOf(valyo(i)) = -1 Then
valyo = origMaxPage
Return False
End If
Try
''IF VALYO IS COMMA REPEATED
If valyo(i) = "," Then
If valyo(i + 1) = "," Then
valyo = origMaxPage
Return False
End If
End If
Catch ex As Exception
valyo = origMaxPage
Return False
End Try
Try
''IF VALYO GREATHER THAN THE MAXPAGE
If valyo(i) = "," Then
Dim twodigit As String = valyo(i + 1) & valyo(i + 2)
Dim numtwodigit As UInt32 = Val(twodigit)
If numtwodigit > origMaxPage Then
valyo = origMaxPage
Return False
End If
End If
Catch ex As Exception
valyo = origMaxPage
Return False
End Try
Next
Return True
End Function
The problem of the code, what if the maxpage is 12, then the user inputed 1,3,5,1111
?
The input may NOT accept negative number like: -1 or -123
Thanks
I assume that at some point you're going to need to get the page numbers anyways, so you should start with that:
Public Function ParsePageNumbers(value As String, maxPage As Integer) As List(Of Integer)
Dim values As New List(Of Integer)()
For Each strNumber As var In value.Split(","C)
Dim intValue As Integer
' if it wasn't an integer or it's greater than the max page, restore the original value
If Not Integer.TryParse(strNumber, intValue) OrElse intValue > maxPage Then
Return Nothing
End If
values.Add(intValue)
Next
Return values
End Function
This function will return Nothing if the pages numbers have invalid values. Then in your actual method you can just call this method and check for Nothing:
Private Function isCELLPageNumb(ByRef valyo As String, ByVal origValue As String) As Boolean
Dim maxPage As Integer = Integer.Parse(origMaxPage)
' if it's not parsible, restore the original value
If ParsePageNumbers(value, maxPage) Is Nothing Then
value = origMaxPage
Return False
End If
' it was all valid
Return True
End Function
Combined to MackieChan solution to parse integer, you should use first Regex
private rgxNumberWithComma As New System.Text.RegularExpressions.Regex("^([0-9]+,?)+$")
Public Function CheckInput(ByVal valyo As String, _
ByVal origMaxPage As Integer) As Boolean
Dim match = rgxNumberWithComma.Match(valyo)
If Not match.Success Then
Return False
Else
Dim numbers as new List(Of Integer) ‘will store added numbers
For Each Item In valyo.Split(","c)
Dim intValue As Integer
‘Check if number is a valid integer
‘Check if number is 0
‘Check if number has already added the number list
‘Check if number is greater that MaxPage
If Not Integer.TryParse(Item, intValue) _
OrElse intValue > origMaxPage _
OrElse intValue = 0 _
OrElse numbers.Contains(IntValue) Then
Return False
Else
‘Item is valid, continue
Numbers.Add(intValue)
End If
Next
End If
Return True
End Function
See Need a Regex for comma separated number list
Try it in your Datagridview EditingControlShowing Event ...
Private Sub DataGridView1_EditingControlShowing(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewEditingControlShowingEventArgs) Handles DataGridView1.EditingControlShowing
Try
If UCase(sCellName) = "PAGENUM" '------> change this with yours
AddHandler e.Control.KeyPress, AddressOf PageKeypress
End If
Catch ex As Exception
'...
End Try
End Sub
Private Sub PageKeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs)
Static sLast As String = ""
Dim k As Byte = Asc(e.KeyChar)
Dim sN As String = "0123456789,"
Dim sO As String = Chr(8) & Chr(13) & Chr(1) & Chr(3) & Chr(22)
Dim nMaxPage As Integer = 12 '-------change this with yours
If Not (sN & sO).Contains(e.KeyChar) Then
e.Handled = True
Else
Select Case e.KeyChar
Case ","
If sLast = "," Then
e.Handled = True
Else
e.Handled = False
sLast = ","
End If
Exit Sub
Case "0"
If sLast = "," Or sLast = "" Then
e.Handled = True
Exit Sub
End If
Case Chr(13) '-- avoid "," in end of text OR YOU CAN REMOVE THIS
If sLast = "," Then e.Handled = True
End Select
If sLast = "," Then sLast = ""
If Val(sLast & e.KeyChar) > nMaxPage Then
e.Handled = True
Exit Sub
End If
sLast &= IIf(sN.Contains(e.KeyChar), e.KeyChar, "")
End If
End Sub

VB.net Need Text Box to Only Accept Numbers

I'm fairly new to VB.net (self taught) and was just wondering if someone out there could help me out with some code. I'm not trying to do anything too involved, just have a TextBox that accepts a numeric value from 1 to 10. I don't want it to accept a string or any number above 10. If someone types a word or character an error message will appear, telling him to enter a valid number. This is what I have; obviously it's not great as I am having problems. Thanks again to anyone who can help.
If TxtBox.Text > 10 Then
MessageBox.Show("Please Enter a Number from 1 to 10")
TxtBox.Focus()
ElseIf TxtBox.Text < 10 Then
MessageBox.Show("Thank You, your rating was " & TxtBox.Text)
Total = Total + 1
ElseIf IsNumeric(TxtBox.Text) Then
MessageBox.Show("Thank you, your rating was " & ValueTxtBox.Text)
End If
ValueTxtBox.Clear()
ValueTxtBox.Focus()
You can do this with the use of Ascii integers. Put this code in the Textbox's Keypress event. e.KeyChar represents the key that's pressed. And the the built-in function Asc() converts it into its Ascii integer.
Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
'97 - 122 = Ascii codes for simple letters
'65 - 90 = Ascii codes for capital letters
'48 - 57 = Ascii codes for numbers
If Asc(e.KeyChar) <> 8 Then
If Asc(e.KeyChar) < 48 Or Asc(e.KeyChar) > 57 Then
e.Handled = True
End If
End If
End Sub
This is what I did in order to handle both key entry and copy/paste.
Private Sub TextBox_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox.KeyPress
If Not Char.IsNumber(e.KeyChar) AndAlso Not Char.IsControl(e.KeyChar) Then
e.Handled = True
End If
End Sub
Private Sub TextBox_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles TextBox.TextChanged
Dim digitsOnly As Regex = New Regex("[^\d]")
TextBox.Text = digitsOnly.Replace(TextBox.Text, "")
End Sub
If you want to allow decimals and negative amount, add
AndAlso Not e.KeyChar = "." AndAlso Not e.keyChar = "-"
to the if statement in the KeyPress section.
Simplest ever solution for TextBox Validation in VB.NET
First, add new VB code file in your project.
Go To Solution Explorer
Right Click to your project
Select Add > New item...
Add new VB code file (i.e. example.vb)
or press Ctrl+Shift+A
COPY & PASTE following code into this file and give it a suitable name. (i.e. KeyValidation.vb)
Imports System.Text.RegularExpressions
Module Module1
Public Enum ValidationType
Only_Numbers = 1
Only_Characters = 2
Not_Null = 3
Only_Email = 4
Phone_Number = 5
End Enum
Public Sub AssignValidation(ByRef CTRL As Windows.Forms.TextBox, ByVal Validation_Type As ValidationType)
Dim txt As Windows.Forms.TextBox = CTRL
Select Case Validation_Type
Case ValidationType.Only_Numbers
AddHandler txt.KeyPress, AddressOf number_Leave
Case ValidationType.Only_Characters
AddHandler txt.KeyPress, AddressOf OCHAR_Leave
Case ValidationType.Not_Null
AddHandler txt.Leave, AddressOf NotNull_Leave
Case ValidationType.Only_Email
AddHandler txt.Leave, AddressOf Email_Leave
Case ValidationType.Phone_Number
AddHandler txt.KeyPress, AddressOf Phonenumber_Leave
End Select
End Sub
Public Sub number_Leave(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs)
Dim numbers As Windows.Forms.TextBox = sender
If InStr("1234567890.", e.KeyChar) = 0 And Asc(e.KeyChar) <> 8 Or (e.KeyChar = "." And InStr(numbers.Text, ".") > 0) Then
e.KeyChar = Chr(0)
e.Handled = True
End If
End Sub
Public Sub Phonenumber_Leave(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs)
Dim numbers As Windows.Forms.TextBox = sender
If InStr("1234567890.()-+ ", e.KeyChar) = 0 And Asc(e.KeyChar) <> 8 Or (e.KeyChar = "." And InStr(numbers.Text, ".") > 0) Then
e.KeyChar = Chr(0)
e.Handled = True
End If
End Sub
Public Sub OCHAR_Leave(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs)
If InStr("1234567890!##$%^&*()_+=-", e.KeyChar) > 0 Then
e.KeyChar = Chr(0)
e.Handled = True
End If
End Sub
Public Sub NotNull_Leave(ByVal sender As Object, ByVal e As System.EventArgs)
Dim No As Windows.Forms.TextBox = sender
If No.Text.Trim = "" Then
MsgBox("This field Must be filled!")
No.Focus()
End If
End Sub
Public Sub Email_Leave(ByVal sender As Object, ByVal e As System.EventArgs)
Dim Email As Windows.Forms.TextBox = sender
If Email.Text <> "" Then
Dim rex As Match = Regex.Match(Trim(Email.Text), "^([0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*#([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,3})$", RegexOptions.IgnoreCase)
If rex.Success = False Then
MessageBox.Show("Please Enter a valid Email Address", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information)
Email.BackColor = Color.Red
Email.Focus()
Exit Sub
Else
Email.BackColor = Color.White
End If
End If
End Sub
End Module
Now use following code to Form Load Event like below.
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
AssignValidation(Me.TextBox1, ValidationType.Only_Digits)
AssignValidation(Me.TextBox2, ValidationType.Only_Characters)
AssignValidation(Me.TextBox3, ValidationType.No_Blank)
AssignValidation(Me.TextBox4, ValidationType.Only_Email)
End Sub
Done..!
You must first validate if the input is actually an integer. You can do it with Integer.TryParse:
Dim intValue As Integer
If Integer.TryParse(TxtBox.Text, intValue) AndAlso intValue > 0 AndAlso intValue < 11 Then
MessageBox.Show("Thank You, your rating was " & TxtBox.Text)
Else
MessageBox.Show("Please Enter a Number from 1 to 10")
End If
Try this:
Private Sub txtCaseID_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtCaseID.KeyPress
If Not Char.IsNumber(e.KeyChar) AndAlso Not Char.IsControl(e.KeyChar) Then e.KeyChar = ""
End Sub
You could avoid any code by using a NumericUpDown control rather than a text box, this automatically only allows numbers and has a max and min.
It also allow accessing the number directly with NumericUpDown1.Value as well as using up and down arrows to set the number.
Also if a number higher/over the max is entered it will jump to the nearest allowed number.
Private Sub MyTextBox_KeyPress(sender As Object, e As System.Windows.Forms.KeyPressEventArgs) Handles MyTextBox.KeyPress
If Not IsNumeric(e.KeyChar) And Not e.KeyChar = ChrW(Keys.Back) Then
e.Handled = True
End If
End Sub
Private Sub textBox5_KeyPress(sender As System.Object, e As System.Windows.Forms.KeyPressEventArgs) Handles textBox5.KeyPress
If Asc(e.KeyChar) <> 8 Then
If Asc(e.KeyChar) < 48 Or Asc(e.KeyChar) > 57 Then
e.Handled = True
End If
End If
End Sub
Private Sub Data_KeyPress(sender As Object, e As KeyPressEventArgs) Handles Data.KeyPress
If (Not e.KeyChar = ChrW(Keys.Back) And ("0123456789.").IndexOf(e.KeyChar) = -1) Or (e.KeyChar = "." And Data.Text.ToCharArray().Count(Function(c) c = ".") > 0) Then
e.Handled = True
End If
End Sub
Dim ch(10) As Char
Dim len As Integer
len = TextBox1.Text.Length
ch = TextBox1.Text.ToCharArray()
For i = 0 To len - 1
If Not IsNumeric(ch(i)) Then
MsgBox("Value you insert is not numeric")
End If
Next
If Not Char.IsNumber(e.KeyChar) AndAlso Not e.KeyChar = "." AndAlso Not Char.IsControl(e.KeyChar) Then
e.KeyChar = ""
End If
This allow you to use delete key and set decimal points
I know this post is old but I wanted to share something I have implemented to turn a TextBox into what I call an IntBox.
First you need to make an extension with:
<Runtime.CompilerServices.Extension()> _
Public Function HandledStringtoInteger(s As String) As Integer
Try
If s = String.Empty Then
Return 0
Else
Return Integer.Parse(s)
End If
Catch
Dim result As String = String.Empty
Dim ReturnInt As Integer
Dim Parsed As Integer
For Each Character In s.ToCharArray
If Character = "-" Then
If s.Substring(0, 1).ToString <> "-" Then
result = Character + result
End If
End If
If Character = "." Then
Exit For
End If
If Integer.TryParse(Character, Parsed) Then
result = result + Parsed.ToString
End If
Next
If result <> String.Empty Then
If Integer.TryParse(result, ReturnInt) Then
Return Integer.Parse(ReturnInt)
Else
If Double.Parse(result) > Double.Parse(Integer.MaxValue.ToString) Then
Return Integer.MaxValue
ElseIf Double.Parse(result) < Double.Parse(Integer.MinValue.ToString) Then
Return Integer.MinValue
Else
Return Integer.Parse(ReturnInt)
End If
End If
Else
Return 0
End If
End Try
End Function
Then make a TextChanged event sub:
Private Sub TextBox_to_IntBox(sender As Object, e As TextChangedEventArgs) Handles YourTextBox.TextChanged
If DirectCast(sender, TextBox).IsKeyboardFocused Then
DirectCast(sender, TextBox).Text = DirectCast(sender, TextBox).Text.HandledStringtoInteger
DirectCast(sender, TextBox).CaretIndex = DirectCast(sender, TextBox).Text.Length
End If
End Sub
Then whenever the user enters text it evaluates the string and only returns numeric values that are within the bounds of a standard Integer. With the "-" character you can change the integer from positive to negative and back again.
If anyone sees anything that can improve this code let me know but my tests show this works fantastic to make an IntBox.
EDIT:
I found another method that can work if you use properties in your code. (Note this will need a separate property per TextBox)
First create the property:
Public Class Properties
Implement INotifyPropertyChanged
Private _Variable as Integer
Public Property YourProperty as Object
get
Return _Variable
end get
set(value as Object)
_Variable = value.ToString.ToInteger 'I will give the ToInteger extension code later
end set
end property
Public Event PropertyChanged As PropertyChangedEventHandler Implements INotifyPropertyChanged.PropertyChanged
Public Sub OnPropertyChange(ByVal e As PropertyChangedEventArgs)
If Not PropertyChangedEvent Is Nothing Then
RaiseEvent PropertyChanged(Me, e)
End If
End Sub
End Class
Then make the binding in your window's main class:
Public WithEvents _YourVariable as New Properties
Public Sub New()
InitializeComponent()
With YourTextBox
.SetBinding(Textbox.TextProperty, New Binding("YourProperty"))
.DataContext = _YourVariable
End With
End Sub
Finally here is the ToInteger Extension Code I set up:
''' <summary>
''' Handles conversion of variable to Integer.
''' </summary>
''' <param name="X"></param>
''' <param name="I">Returned if conversion fails.</param>
''' <returns>Signed 32bit Integer</returns>
''' <remarks></remarks>
<Runtime.CompilerServices.Extension()> _
Public Function toInteger(Of T)(ByRef X As T, Optional I As Integer = 0) As Integer
Dim S As String = X.ToString
Try
If S = String.Empty Then
Return I
Else
Return Integer.Parse(S)
End If
Catch
Dim result As String = String.Empty
Dim ReturnInt As Integer
Dim Parsed As Byte
For Each Character In S.ToCharArray
If Character = "-" Then
If S.Substring(0, 1).ToString <> "-" Then
result = Character + result
End If
End If
If Character = "." Then
Exit For
End If
If Byte.TryParse(Character, Parsed) Then
result = result + Parsed.ToString
End If
Next
If result <> String.Empty Then
If Integer.TryParse(result, ReturnInt) Then
Return Integer.Parse(ReturnInt)
Else
If Double.Parse(result) > Double.Parse(Integer.MaxValue.ToString) Then
Return Integer.MaxValue
ElseIf Double.Parse(result) < Double.Parse(Integer.MinValue.ToString) Then
Return Integer.MinValue
Else
Return Integer.Parse(ReturnInt)
End If
End If
Else
Return I
End If
End Try
End Function
With all these combined whenever they type something into the box it will act as if it were a textbox but when they change focus the ToInteger extension will set the value as an integer into the property and return it to the textbox.
Meaning that if the operator entered "-1w3" after focus changes it will return as "-13" automatically.
This may be too late, but for other new blood on VB out there, here's something simple.
First, in any case, unless your application would require, blocking user's key entry is somehow not a good thing to do, users may misinterpret the action as problem on the hardware keyboard and at the same time may not see where their keypreesed entry error came from.
Here's a simple one, let user's freely type their entry then trap the error later:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim theNumber As Integer
Dim theEntry As String = Trim(TextBox1.Text)
'This check if entry can be converted to
'numeric value from 0-10, if cannot return a negative value.
Try
theNumber = Convert.ToInt32(theEntry)
If theNumber < 0 Or theNumber > 10 Then theNumber = -1
Catch ex As Exception
theNumber = -1
End Try
'Trap for the valid and invalid numeric number
If theNumber < 0 Or theNumber > 10 Then
MsgBox("Invalid Entry, allows (0-10) only.")
'entry was invalid return cursor to entry box.
TextBox1.Focus()
Else
'Entry accepted:
' Continue process your thing here...
End If
End Sub
I have the solution where it will check whether the text is range 1 to 10 : [1-9] will check for the range from 1 to 9. I use one more condition to check for 10.
If txtBox.Text Like "[1-9]" Or txtBox.Text Like "10" Then
MessageBox.Show("true")
Else
MessageBox.Show("false")
End If
First of all set the TextBox's MaxLength to 2 that will limit the amount of text entry in your TextBox. Then you can try something like this using the KeyPress Event. Since you are using a 2 digit maximum (10) you will need to use a Key such as Enter to initiate the check.
Private Sub TextBox1_KeyPress(sender As System.Object, e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
Dim tb As TextBox = CType(sender, TextBox)
If Not IsNumeric(e.KeyChar) Then 'Check if Numeric
If Char.IsControl(e.KeyChar) Then 'If not Numeric Check if a Control
If e.KeyChar = ChrW(Keys.Enter) Then
If Val(tb.Text) > 10 Then 'Check Bounds
tb.Text = ""
ShowPassFail(False)
Else
ShowPassFail(True)
End If
e.Handled = True
End If
Exit Sub
End If
e.Handled = True
ShowPassFail(False)
End If
End Sub
Private Sub ShowPassFail(pass As Boolean)
If pass Then
MessageBox.Show("Thank you, your rating was " & TextBox1.Text)
Else
MessageBox.Show("Please Enter a Number from 1 to 10")
End If
TextBox1.Clear()
TextBox1.Focus()
End Sub
Public Function Isnumber(ByVal KCode As String) As Boolean
If Not Isnumeric(KCode) And KCode <> ChrW(Keys.Back) And KCode <> ChrW(Keys.Enter) And KCode <> "."c Then
MsgBox("Please Enter Numbers only", MsgBoxStyle.OkOnly)
End If
End Function
Private Sub txtBalance_KeyPress(ByVal sender As System.Object, ByVal e As
System.Windows.Forms.KeyPressEventArgs) Handles txtBalance.KeyPress
If Not Isnumber(e.KeyChar) Then
e.KeyChar = ""
End If
End Sub
This worked for me... just clear the textbox completely as non-numeric keys are pressed.
Private Sub TextBox2_TextChanged(sender As Object, e As EventArgs) Handles TextBox2.TextChanged
If IsNumeric(TextBox2.Text) Then
'nada
Else
TextBox2.Clear()
End If
End Sub
Copy this function in any module inside your vb.net project.
Public Function MakeTextBoxNumeric(kcode As Integer, shift As Boolean) As Boolean
If kcode >= 96 And kcode <= 105 Then
ElseIf kcode >= 48 And kcode <= 57
If shift = True Then Return False
ElseIf kcode = 8 Or kcode = 107 Then
ElseIf kcode = 187 Then
If shift = False Then Return False
Else
Return False
End If
Return True
End Function
Then use this function inside your textbox_keydown event like below:
Private Sub txtboxNumeric_KeyDown(sender As Object, e As KeyEventArgs) Handles txtboxNumeric.KeyDown
If MakeTextBoxNumeric(e.KeyCode, e.Shift) = False Then e.SuppressKeyPress = True
End Sub
And yes. It works 100% :)
You can use the onkeydown Property of the TextBox for limiting its value to numbers only.
<asp:TextBox ID="TextBox1" runat="server" onkeydown = "return (!(event.keyCode>=65) && event.keyCode!=32);"></asp:TextBox>
!(keyCode>=65) check is for excludng Alphabets.
keyCode!=32 check is for excluding Space character inbetween the numbers.
If you want to exclude Symbols also from entering into the textbox, then include the below condition also in the 'onkeydown' property.
!(event.shiftKey && (event.keyCode >= 48 && event.keyCode <= 57))
Thus the TextBox will finally become
<asp:TextBox ID="TextBox1" runat="server" onkeydown = "return (!(event.keyCode>=65) && event.keyCode!=32 && !(event.shiftKey && (event.keyCode >= 48 && event.keyCode <= 57)));"></asp:TextBox>
Explanation:
KeyCode for 'a' is '65' and 'z' is '90'.
KeyCodes from '90' to '222' which are other symbols are also not needed.
KeyCode for 'Space' Key is '32' which is also not needed.
Then a combination of 'Shift' key and 'Number' keys (which denotes Symbols) also not needed. KeyCode for '0' is '48' and '9' is '57'.
Hence all these are included in the TextBox declaration itself which produces the desired result.
Try and see.
This was my final... It gets around all the type issues also:
Here is a simple textbox that requires a number:
public Sub textbox_memorytotal_TextChanged(sender As Object, e As EventArgs) Handles textbox_memorytotal.TextChanged
TextboxOnlyNumbers(sender)
End Sub
and here is the procedure that corrects all bad input:
Public Sub TextboxOnlyNumbers(ByRef objTxtBox As TextBox)
' ONLY allow numbers
If Not IsNumeric(objTxtBox.Text) Then
' Don't process things like too many backspaces
If objTxtBox.Text.Length > 0 Then
MsgBox("Numerical Values only!")
Try
' If something bad was entered delete the last character
objTxtBox.Text = objTxtBox.Text.Substring(0, objTxtBox.Text.Length - 1)
' Put the cursor and the END of the corrected number
objTxtBox.Select(objTxtBox.Text.Length + 1, 1)
Catch ex As Exception
End Try
End If
End If
End Sub
Use this in your Textbox Keydown event.
Private Sub TextBox1_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles TextBox1.KeyDown
'you can enter decimal "if nonNumberEntered(e, TextBox1, True) then"
'otherwise just numbers "if nonNumberEntered(e, TextBox1) then"
If nonNumberEntered(e, TextBox1, True) Then
e.SuppressKeyPress = True
End If
If e.KeyCode = Keys.Enter Then
'put your code here
End If
End Sub
Copy this function in any module inside your vb.net project.
Public Function nonNumberEntered(ByVal e As System.Windows.Forms.KeyEventArgs, _
ByVal ob As TextBox, _
Optional ByVal decim As Boolean = False) As Boolean
nonNumberEntered = False
If decim Then
' Determine whether the keystroke is a number from the top of the keyboard.
If e.KeyCode < Keys.D0 OrElse e.KeyCode > Keys.D9 Then
' Determine whether the keystroke is a number from the keypad.
If e.KeyCode < Keys.NumPad0 OrElse e.KeyCode > Keys.NumPad9 Then
If e.KeyCode <> Keys.Decimal And e.KeyCode <> Keys.OemPeriod Then
If e.KeyCode <> Keys.Divide And e.KeyCode <> Keys.OemQuestion Then
' Determine whether the keystroke is a backspace.
If e.KeyCode <> Keys.Back And e.KeyCode <> Keys.Delete _
And e.KeyCode <> Keys.Left And e.KeyCode <> Keys.Right Then
' A non-numerical keystroke was pressed.
nonNumberEntered = True
End If
ElseIf ob.Text.Contains("/") Or ob.Text.Length = 0 Then
nonNumberEntered = True
End If
ElseIf ob.Text.Contains(".") Or ob.Text.Length = 0 Then
nonNumberEntered = True
End If
End If
End If
Else
' Determine whether the keystroke is a number from the top of the keyboard.
If e.KeyCode < Keys.D0 OrElse e.KeyCode > Keys.D9 Then
' Determine whether the keystroke is a number from the keypad.
If e.KeyCode < Keys.NumPad0 OrElse e.KeyCode > Keys.NumPad9 Then
' Determine whether the keystroke is a backspace.
If e.KeyCode <> Keys.Back And e.KeyCode <> Keys.Delete _
And e.KeyCode <> Keys.Left And e.KeyCode <> Keys.Right Then
' A non-numerical keystroke was pressed.
nonNumberEntered = True
End If
End If
End If
End If
'If shift key was pressed, it's not a number.
If Control.ModifierKeys = Keys.Shift Then
nonNumberEntered = True
End If
End Function
This will allow numbers like 2/4 or numbers like 3.5 to be entered in your textbox if using decim "nonNumberEntered(e,Textbox1, True)".
Allows only numbers to be entered in textbox if using "nonNumberEntered(e,Textbox1, False)" or "nonNumberEntered(e,Textbox1)".
Edit: added text.
I had a similar use requirement recently for a TextBox which could only take numbers.
In the end I used a MaskedTextBox instead of a TextBox. You define a "mask" for the textbox and it will only accept characters which you have defined - in this case, numbers. The downside is that it leaves a bit of an ugly line within the TextBox;
What I loved about the MaskedTextBox was it was so customisable. If, for whatever reason you wanted a TextBox to only accept an input in the format of 3 ints followed by 2 letters, all you need to do is set the TextMask to 000LL. There are a load of pre-defined masks within Visual Studio, and the full documentation can be found here.
Now, I know this doesn't fully solve your issue, but the use of a MaskedTextBox takes away a huge part of the complexity of the problem. You can now guarantee that the contents of the MaskedTextBox will only ever be an Int, allowing you to run a simple If statement to ensure the value is =<10
I know this post is old but I want to share my code.
Private Sub txtbox1_TextChanged(sender As Object, e As EventArgs) Handles txtbox1.TextChanged
If txtbox1.Text.Length > 0 Then
If Not IsNumeric(txtbox1.Text) Then
Dim sel As Integer = txtbox1.SelectionStart
txtbox1.Text = txtbox1.Text.Remove(sel - 1, 1)
txtbox1.SelectionStart = sel - 1
End If
End If
End Sub
On each entry in textbox (event - Handles RestrictedTextBox.TextChanged), you can do a try to caste entered text into integer, if failure occurs, you just reset the value of the text in RestrictedTextBox to last valid entry (which gets constantly updating under the temp1 variable).
Here's how to go about it. In the sub that loads with the form (me.load or mybase.load), initialize temp1 to the default value of RestrictedTextBox.Text
Dim temp1 As Integer 'initialize temp1 default value, you should do this after the default value for RestrictedTextBox.Text was loaded.
If (RestrictedTextBox.Text = Nothing) Then
temp1 = Nothing
Else
Try
temp1 = CInt(RestrictedTextBox.Text)
Catch ex As Exception
temp1 = Nothing
End Try
End If
At any other point in form:
Private Sub textBox_TextChanged(sender As System.Object, e As System.EventArgs) Handles RestrictedTextBox.TextChanged
Try
temp1 = CInt(RestrictedTextBox.Text) 'If user inputs integer, this will succeed and temp will be updated
Catch ex As Exception
RestrictedTextBox.Text = temp1.ToString 'If user inputs non integer, textbox will be reverted to state the state it was in before the string entry
End Try
End Sub
The nice thing about this is that you can use this to restrict a textbox to any type you want: double, uint etc....
every text box has a validating and validated event you can use then as follows :-
Private Sub PriceTxt_Validating(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles PriceTxt.Validating
If Not IsNumeric(PriceTxt.Text) Then
PriceTxt.BackColor = Color.Red
MsgBox("The Price Should Be Numeric Only , Enter Again", vbCritical)
PriceTxt.Text = ""
PriceTxt.BackColor = Color.White
End If
End Sub
I know it's old.. I'll just leave this code here for the sake of convenience.
Integer only:
Public Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
With TextBox1
If IsNumeric(.Text) Then .Text = .Text.Select(Function(x) If(IsNumeric(x), x, "")) : .SelectionStart = .TextLength
End With
' etc..
End Sub
Accepts Double:
Public Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
With TextBox1
If IsNumeric(.Text) Then .Text = .Text.Select(Function(x) If(IsNumeric(x) Or x = ".", x, "")) : .SelectionStart = .TextLength
End With
' etc..
End Sub
Accepts basic operations + - * /, parentheses ( ) [ ] { } and Double:
Public Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
With TextBox1
If IsNumeric(.Text) Then .Text = .Text.Select(Function(x) If(IsNumeric(x) Or ".+-*/()[]{}".Contains(x), x, "")) : .SelectionStart = .TextLength
End With
' etc..
End Sub
You Can use Follow code Textbox Keypress Event:
Private Sub txtbox1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtbox1.KeyPress
Try
If Val(txtbox1.text) < 10 Then
If Char.IsLetterOrDigit(e.KeyChar) = False And Char.IsControl(e.KeyChar) = False Then
e.Handled = True
End If
Else
e.Handled = True
End If
Catch ex As Exception
ShowException(ex.Message, MESSAGEBOX_TITLE, ex)
End Try
End Sub
This code allow numbers only and you can enter only number between 1 to 10.
Very simple piece of code that works for me.
Private Sub Textbox1_KeyPress(sender As Object, e As KeyPressEventArgs) Handles textbox1.KeyPress
If Asc(e.KeyChar) > 58 Then
e.KeyChar = ""
End If
End Sub
Here's what works for me. It allows backspace, del, as well as numbers from the top row of the keyboard and the number pad. It excludes the + and - signs.
Private Sub tbMQTTPort_KeyDown(sender As Object, e As KeyEventArgs) Handles tbMQTTPort.KeyDown
Dim kc As New KeyConverter
Dim Regex = New Regex("[^0-9]+")
e.Handled = Regex.IsMatch(kc.ConvertToInvariantString(e.Key).Replace("NumPad", ""))
End Sub