Validation Class(dll) - vb.net

İ m tring to do a validation dll for may textbox. my dll's codes like this
Public Class validatedll
Function onlynumbers(ByVal r As String)
Dim list As String, character As String
Dim i As Integer
list = "1234567890"
i = 1
If r <> "" Then
cntinue:
If i > 10 Then
MsgBox("invalid character. Last character will be delete !")
r = Mid(r, 1, Len(r) - 1)
Return r
Exit Function
End If
character = Mid(list, i, 1)
If Microsoft.VisualBasic.Right(r, 1) = character Then Exit Function
i = i + 1
GoTo cntinue
Else
Exit Function
End If
End Function
End Class
And i m useing this dll in my project like this
Imports ModifiedTextbox
Public Class Form1
Public validate As New validatedll
Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
' TextBox1.Text = validate.onlynumbers(TextBox1.Text)
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
TextBox1.Text = validate.onlynumbers(TextBox1.Text)
End Sub
End Class
My problem is, if i use this dll in TextBox1_TextChanged event, Textbox1's text showing to me nothing because dll is not returning numbers. İf i use this code with button, code is working and deleting last character if a letter.
How can i use this dll in textchanged event? pls help to me.
My best regards

The main reason your weren't getting a return is whenever your loop found the right character it exited.
A few things:
A function should always have an As clause to specify the return type. You may remember the return today what about a year from now?
Never use GoTo. VB.net has several functional loops that will do pretty whatever you like.
Assuming that you want to extend this to support other validations you might want to consider another approach:
Public Class validatedll
Sub onlynumbers(tb As TextBox)
While Not tb.Text = "" AndAlso Not Double.TryParse(tb.Text, vbNull)
tb.Text = tb.Text.Remove(tb.Text.Length - 1)
tb.SelectionStart = tb.Text.Length
End While
End Sub
End Class
I made it a sub that gets passed a reference to the textbox. This keeps the mechanism of your validation more compartmentalized. This will also make it easier if you decide to extend this class to be a custom control.
This tests if the string is a number, and keeps subtracting characters until it's empty or is a number. This will work for on the fly validation or on exit validation.

i resolve my problem. Maybe somebody needs that. You can add which chars to wanna allow with orelse;
Function onlynumbers(ByVal chars As String, ByVal exclmtn As Boolean, Optional title As String = "Title what you want")
If chars = "" Then Exit Function
If _
Microsoft.VisualBasic.Right(chars, 1) = "1" OrElse _
Microsoft.VisualBasic.Right(chars, 1) = "2" OrElse _
Microsoft.VisualBasic.Right(chars, 1) = "3" OrElse _
Microsoft.VisualBasic.Right(chars, 1) = "4" OrElse _
Microsoft.VisualBasic.Right(chars, 1) = "5" OrElse _
Microsoft.VisualBasic.Right(chars, 1) = "6" OrElse _
Microsoft.VisualBasic.Right(chars, 1) = "7" OrElse _
Microsoft.VisualBasic.Right(chars, 1) = "8" OrElse _
Microsoft.VisualBasic.Right(chars, 1) = "9" OrElse _
Microsoft.VisualBasic.Right(chars, 1) = "0" Then
Return chars
Exit Function
Else
If exclmtn = False Then
chars = Mid(chars, 1, Len(chars) - 1)
Return chars
Exit Function
End If
If exclmtn = True Then
MsgBox("invalid. last char ll delete !", , title)
chars = Mid(chars, 1, Len(chars) - 1)
Return chars
Exit Function
End If
End If
End Function

Related

Using vb.net Count all occurrences of vbCrLf in TextBox

I have a TextBox that I am trying to count all the occurrences of vbCrLf.
The counting is working, the issue is every time a vbCrLf is issued I would like to subtract 33 from some Integer.
The code as written now only subtracts the number of vbCrLf, NOT the number + 33.
Question is how to subtract 33 every time the Enter Key is pressed and a vbCrLf is issued ?
I have posted Updated Code The Question Was Answered and Issues SOLVED
I have also added additional code that enhances the management of the TextBox
You will need these Imports
Imports System.IO
Imports System.Text
Public Class frmThree
Dim path As String = "C:/Users/Me/source/repos/TestForms/TestForms/Resource/"
Dim total As Integer
Dim vbLfTotal As Integer
Dim chrPermited As Integer = 333 'chrPermited
Private Sub btnBack_Click(sender As Object, e As EventArgs) Handles btnBack.Click
Me.Close()
frmOne.Show()
End Sub
Private Sub tbHaveOne_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tbHaveOne.TextChanged
Dim spaceCount, letterCount, carReturn As Integer
spaceCount = 0
letterCount = 0
carReturn = 0
Dim str As String = tbHaveOne.Text
For Each chr As Char In str
If chr = vbLf Then
carReturn += 1
ElseIf Char.IsLetterOrDigit(chr) Then
letterCount += 1
ElseIf Char.IsWhiteSpace(chr) Then
spaceCount += 1
End If
Next
vbLfTotal = carReturn * 29
total = chrPermited - letterCount - spaceCount - vbLfTotal
tbHaveTwo.ForeColor = Color.Black
tbHaveTwo.Text = total & " More Character Can Be Entered"
While total < 10
tbHaveTwo.Clear()
tbHaveTwo.ForeColor = Color.Red
tbHaveTwo.Text = "Only " & total & " More Character Can Be Entered"
Exit While
End While
If total = 5 Then
PlaySystemSound()
End If
If total < 1 Then
tbHaveTwo.Clear()
tbHaveTwo.Text = "No More Data Entry" & total
Call ansQ()
End If
End Sub
Sub PlaySystemSound()
My.Computer.Audio.PlaySystemSound(
System.Media.SystemSounds.Hand)
End Sub
Public Sub ansQ()
Const Msg As String = "YES Save Data" + vbCrLf + vbNewLine + "NO CANCEL"
Const Title As String = "Save or Exit"
Const Style = vbYesNo + vbQuestion + vbDefaultButton2
Dim result = MsgBox(Msg, Style, Title)
If result = vbYes Then
Call writeDATA()
ElseIf result = vbNo Then
'tbHaveOne.ReadOnly = True
'tbHaveOne.Enabled = False
tbHaveTwo.Text = "NO Was Selected"
'result = 0
End If
End Sub
Public Shared Sub tbHaveOne_KeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles tbHaveOne.KeyDown
'NOTE this Sub is Shared It seems to run all the time like a listener
If e.KeyCode = Keys.Enter And frmThree.total < 40 Then
e.SuppressKeyPress = True
End If
End Sub
The TextBox.Lines.Count returns the count of the lines separated by newline characters (ControlChars.NewLine or Environment.NewLine when you hit the Enter key.) and not the count of the word-wrapped lines in a multiline TextBox. If you set the WordWrap property to False you will see the difference. See the TextBoxBase.Lines remarks section.
You could call the SendMessage method and the EM_GETLINECOUNT message if you need to get the count of the lines regardless whether they are word-wrapped or separated new lines:
Imports System.Runtime.InteropServices
Private Const EM_GETLINECOUNT As UInteger = &HBA
<DllImport("user32.dll")>
Private Shared Function SendMessage(ByVal hWnd As IntPtr,
ByVal msg As Integer,
ByVal wp As IntPtr,
ByVal lp As IntPtr) As IntPtr
End Function
Private Sub PrintCounts()
Dim c = tbHaveOne.Text.
Aggregate(New With {
.WhiteSpaces = 0, .Lf = 0, .NewLines = 0, .Lines = 0, .Others = 0
},
Function(x, y)
x.Lf += If(y = ControlChars.Cr, 1, 0)
x.WhiteSpaces += If(Char.IsSeparator(y), 1, 0)
x.Others += If(Not Char.IsWhiteSpace(y), 1, 0)
Return x
End Function)
c.NewLines = tbHaveOne.Lines.Count
c.Lines = SendMessage(tbHaveOne.Handle, EM_GETLINECOUNT,
IntPtr.Zero, IntPtr.Zero).ToInt32
tbHaveTwo.Text = $"WhiteSpaces: {c.WhiteSpaces} Lf: {c.Lf} " +
$"New Lines: {c.NewLines} Lines {c.Lines} Others: {c.Others}"
End Sub
Private Sub tbHaveOne_TextChanged(sender As Object,
e As EventArgs) Handles tbHaveOne.TextChanged
PrintCounts()
End Sub
Please note:
The Char.IsSeparator method is used to get the count of the white spaces since the Char.IsWhiteSpace method will return True when evaluating; vbCr, vbLf, vbCrLf, vbTab, ...etc. Alternatively, you can combine the Char.IsWhiteSpace and the Char.IsControl methods to evaluate the white spaces. The Remarks section has more.
The Others is the count of everything else including the letters, digits, punctuations, symbols...etc. You may wont to examine the other Char.IsXXX methods of the Char structure.
Check out the values of the Lines and NewLines fields as you type.
You can't check if the current character is vbcrlf because CRLF is two characters. Just check for the LF, this way if you ever use the logic on a file prepared by a unix system, it still works (unix has LF, Windows has CRLF)
Private Sub tbHaveOne_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tbHaveOne.TextChanged
Dim spaceCount = 0
Dim letterCount = 0
Dim lineCount = 0
For Each c As Char In tbHaveOne.Text
If c = vbLf Then
lineCount += 1
ElseIf Char.IsLetterOrDigit(c) Then
letterCount += 1
ElseIf Char.IsWhiteSpace(c) Then
spaceCount += 1
End If
Next c
someInteger -= (lineCount * 33)
The System.Char has static methods that check characters are in certain Unicode ranges - for your letter count you were counting anything that wasn't a space, including carriage returns, punctuation and other things that aren't letters, as letters. You're free to carry on doing that if you want but it'll maybe lead to a bit of a confusing count if you triple count the newlines
The counting is working the issue is every time a vbCrLf is issued I would like to subtract 33 from some Integer
The code as written now only subtracts the number of vbCrLf NOT the number + 33
I didn't quite get this. You say you want to subtract 33 every time there is a new line, which is what I've done. The second sentence reads like the requirement is to subtract the (number of new lines + 33) from someInteger. If this is what you want to do, change the * on the last line to +
Question is how to subtract 33 every time the Enter Key is pressed and a vbCrLf is issued ?
This is a different thing entirely to "count all occurrences of"; it isn't to do with counting the lines in a textbox, and you can't do it from such code. Counting the number of times the user has ever pressed enter in a textbox needs a hook to the event raised when a user pressed a key while the box had focus. Add a handler for the KeyPress or KeyDown event:
Private Sub tbHaveOne_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles tbHaveOne.KeyPress 'KeyEventArgs for KeyDown event
If e.KeyChar = vbCr Then 'use e.KeyCode = Keys.Enter in KeyDown event
someInteger -= 33
End If
End Sub
We have a lot of great Discussion and Fixed Answers on this question
One of the questions in the discussion was how to handle punctuation and special characters
We would like to offer this code as a way to manage both punctuation and special characters
Dim spaceCount, letterCount, carReturn, punCount, syCount As Integer
spaceCount = 0
letterCount = 0
carReturn = 0
punCount = 0
syCount = 0
Dim str As String = tbHaveOne.Text
For Each chr As Char In str
If chr = vbLf Then
carReturn += 1
ElseIf Char.IsLetterOrDigit(chr) Then
letterCount += 1
ElseIf Char.IsWhiteSpace(chr) Then
spaceCount += 1
ElseIf Char.IsPunctuation(chr) Then
punCount += 1
ElseIf Char.IsSymbol(chr) Then
syCount += 1
End If
Next
vbLfTotal = carReturn * 29
total = chrPermited - letterCount - spaceCount - vbLfTotal - punCount - syCount
tbHaveTwo.ForeColor = Color.Black
tbHaveTwo.Text = total & " More Character Can Be Entered"

Textbox validation, cursor skipping to the start of the text

In vb.net, I have the following code to validate acceptable characters that can be entered into a textbox.
Private Sub txt_mobile_phone_TextChanged(sender As Object, e As EventArgs) Handles txt_mobile_phone.TextChanged
Dim s As String = ""
For Each C As Char In txt_mobile_phone.Text
If (C >= "0" And C <= "9") OrElse (C = " ") OrElse (C = "-") OrElse (C = "+") Then
s &= C
End If
Next
txt_mobile_phone.Text = s
End Sub
The problem is, is that when someone enters an invalid character (for example, an exclamation mark '!'), the cursor position then skips to the start of the text string, and all further characters are entered at the start.Is there a way to make it so that it ignores invalid characters and carries on typing from the end of the string?
If possible, without using txt_mobile_phone.SelectionStart = txt_mobile_phone.Text.Length -1 as this means that clicking the middle of the string to add to the middle of it will break (which currently is possible)
The issue is that you are firing an event on the TextChanged, that is int he middle of something. For your purpose, to validate entries, you have got the KeyPress event, whereby you have the e.Handle to block entries.
Find the example below, which I applied in my application to accept only numeric and should not accept spaces;
Private Sub txt_mobile_phone_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txt_mobile_phone.KeyPress, _
AcEmpNo.KeyPress
' Accept only numeric values
If (e.KeyChar < Chr(48) OrElse e.KeyChar > Chr(57)) _
AndAlso e.KeyChar <> Chr(8) Then
e.Handled = True
End If
End Sub
You can also use Char convertor if you don't know the code like;
e.KeyChar = ChrW(Keys.Space)
Hope this helps.

Moving through datagridview rows on keypress

I'm trying to go through datagridview rows where the cell value starts with the same keychar the user pressed. Code bellow works, but It wont move selection to next row starting with same letter when I press same letter second, third time...
Private Sub dataGridView1_KeyPress(sender As Object, e As KeyPressEventArgs) Handles dgw.KeyPress
If [Char].IsLetter(e.KeyChar) Then
For i As Integer = 0 To (dgw.Rows.Count) - 1
If dgw.Rows(i).Cells(1).Value.ToString().StartsWith(e.KeyChar.ToString(), True, CultureInfo.InvariantCulture) Then
If lastKey = e.KeyChar And lastIndex < i Then
Continue For
End If
lastKey = e.KeyChar
lastIndex = i
dgw.Rows(i).Cells(1).Selected = True
Return
End If
Next
End If
End Sub
Seems like a flaw in the logic. You press key, save index and break. Then you press the same key. And if lastIndex is lesser than i you continue. Which means it will only select the first row it finds with a lesser value than the last one. Change to lastindex > i and you should be fine.
You can with the code you have written never get anything else than the first line matching the key. After that it doesn't matter how many times you press.
I know that is too old this post... anyway I've found a workaround for this and maybe it will be useful for someone.
public lastkey as string
Private Sub dataGridView1_KeyPress(sender As Object, e As KeyPressEventArgs) Handles dgw.KeyPress
Dim input = StrConv(e.keychar.toString()
lastkey += input
Dim found as Boolean
if StrConv(dgw.currentCell.Value.toString.Substring(0,1), VbStrConv.UpperCase) = input then
dim curIndex = dgw.currentRow.Index
if curIndex < dgw.rows.count - 1 then
dgw.ClearSelection()
curIndex += 1
dgw.currentCell = dgw.rows(curIndex).Cells(0)
dgw.rows(curIndex).selected = true
end if
else
dgv_jumpRecord(lastkey,found)
if not found then
lastkey = input
dgv_jumpRecord(lastkey,found)
end if
End if
End Sub
Public Sub dgv_jumpRecord(byVal lastkey as String, ByRef found as boolean)
For i As Integer = 0 To (dgw.Rows.Count) - 1
dim rowText = dgw.Rows(i).Cells(1).Value.ToString
If StrConv(rowText.ToString(),VbStrConv.UpperCase).StartsWith(lastkey) Then
dgw.ClearSelection()
dgw.CurrentCell = dgw.rows(i).Cells(0)
dgw.rows(i).selected = true
found = true
Exit Sub
End If
Next
found = false
End Sub

validating alphanumeric input in textbox [VB2010]

im newbie here, im using vb2010, i just need some help guys.
here's my problem.
i want to validate user's input on my textbox, when user input like this "1a1:b2b:3c3", my project should accept it. but when user input like this "1a1b2b3c3", it will show a msgbox that the format must be "XXX:XXX:XXX".thanks for help in advance.
I done up a very quick example for you, more than enough to get you on the right track. I could have done it a different way, but I am sure this will get you going. I used MaxLength to determine that the user input at least 9 characters and if not let them know. I also made a function that passes the textbox's text into this and will go ahead and format it for you; saves the user time... besides we just need to make sure user primarily enters at least 9 characters anyways if I am correct... Good Luck!
Public Class Form1
Private strValidatedText As String = String.Empty
Private blnValid As Boolean = False
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'Make sure user can only enter up to 9 values...
With txtInput
.MaxLength = 9
.TextAlign = HorizontalAlignment.Center
End With
End Sub
Private Sub btnValidate_Click(sender As Object, e As EventArgs) Handles btnValidate.Click
Dim strTextBox As String = txtInput.Text
strValidatedText = ValidateText(strTextBox)
Select Case blnValid
Case True
MessageBox.Show("It's valid! " & strValidatedText)
txtInput.Clear()
txtInput.Focus()
Case Else
MessageBox.Show(strValidatedText)
txtInput.Clear()
txtInput.Focus()
End Select
End Sub
Private Function ValidateText(ByVal strText As String)
Dim strNewText As String = String.Empty
If strText.Length = 9 Then
strNewText = (strText.Substring(0, 3) & ":" & strText.Substring(3, 3) & ":" & strText.Substring(6, 3))
blnValid = True
Else
strNewText = "There must be at least 9 characters in the textbox!"
blnValid = False
End If
Return strNewText
End Function
End Class
Also at that point in the "Select Case blnValid", you can do what ever you would like with that string because it's global...
MrCodeXeR
I would suggest you to use MaskedTextBox class, it will help you to take a formatted input from user. Have a look at this example.
I tried it with following code and it works fine in VB 2010. Just use this code before your variable declaration:
If TextBox1.Text = "" Then 'check if the textbox has a value
MsgBox("Please Enter ID Number")
Return 'will return to the app
ElseIf Not IsNumeric(TextBox1.Text) Then 'check if the entered value is a number
MsgBox("ID Must Be A Number")
Return

How to filter textbox input to numeric only?

How do I suppress all data except numeric?
This is not working on KeyDown():
If e.KeyData < Keys.D0 Or e.KeyData > Keys.D9 Then
e.Handled = True
End If
There are many ways to do this. I've had a quick stab at it and go this which works. I have used the KeyPress sub for the textbox, and pass each keypress to the IsNumber function.
NOTE: I have allowed the backspace key to be used in case you make a mistake with the numbers and want to deleted.
Take out the If e.KeyChar <> ChrW(Keys.Back) Then / End If part if you dont need the backspace.
Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
If e.KeyChar <> ChrW(Keys.Back) Then
If Char.IsNumber(e.KeyChar) Then
Else
e.Handled = True
End If
End If
End Sub
You can check Char.IsDigit(e.KeyChar), but the best thing to do in this case is to create a subclass of TextBox and override IsInputChar(). That way you have a reusable TextBox control that you can drop anywhere so you don't have to re-implement the logic.
(My VB is a bit rusty...)
Public Class NumericTextBox : Inherits TextBox
Protected Overrides Function IsInputChar(Byval charCode As Char) As Boolean
If (Char.IsControl(charCode) Or Char.IsDigit(charCode)) Then
Return MyBase.IsInputChar(charCode)
Else
Return False
End If
End Function
End Class
This code will help you to restrict multiple TEXTBOX to accept only NUMERIC VALUE and BACKSPACE key. However you can remove If e.KeyChar <> ChrW(Keys.Back) Then and End If value from code when you don't want to accept backspace key. Enhanced version of the kevchadders solution in this thread.
Private Sub TextBox_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress, TextBox2.KeyPress, TextBox3.KeyPress
If e.KeyChar <> ChrW(Keys.Back) Then
If Char.IsNumber(e.KeyChar) Then
Else
e.Handled = True
End If
End If
End Sub
Will help you...
Public Function IsNumericTextbox(ByVal sender As TextBox, ByVal KeyChar As Char) As Boolean
'set TRUE: cause a exception when the keychar is not Allowed into vars: allowedChars, allowedOneChar, allowedExceptionChar
Dim UseThrowDebuggy As Boolean = False
Dim allowedChars As String = "0123456789"
Dim allowedOnceChar As Char() = {"."}
Dim allowedExceptionChar As Keys() = {Keys.Back}
Dim idxAllowedNotFound As Integer
Dim idxCountOne As Integer = 0
idxAllowedNotFound = allowedChars.IndexOf(KeyChar)
If idxAllowedNotFound = True Then
'AllowedOnce
For Each _c As Char In allowedOnceChar
If _c = KeyChar Then
'Count Check
For Each _cc As Char In sender.Text
If _c = _cc Then idxCountOne += 1
Next
If idxCountOne = 0 Then
Return False
Else
Return True
End If
End If
Next
'Exceptions
For i As Integer = 0 To allowedExceptionChar.Count - 1
If Asc(KeyChar) = Convert.ToUInt32(allowedExceptionChar(i)) Then Return False
Next
'Not Throw
If UseThrowDebuggy = False Then
If Char.IsNumber(KeyChar) Then
Return False
Else
Return True
End If
End If
'Outside to end for throw
Else
'AllowedChars
Return False
End If
Dim _kc As String = ControlChars.NewLine & "Char: " & KeyChar & ControlChars.NewLine & "Asc: " & Asc(KeyChar) & ControlChars.NewLine
Throw New Exception("UseThrowDebuggy found a unknow KeyChar: " & _kc)
End Function
For use my function add this code into a textbox_keypress:
e.Handled = IsNumericTextbox(sender, e.KeyChar)
Public Class NumericTextBox : Inherits System.Windows.Forms.TextBox
Protected Overrides Sub OnKeyPress(e As Windows.Forms.KeyPressEventArgs)
If Char.IsDigit(e.KeyChar) Or
Char.IsControl(e.KeyChar) Or
e.KeyChar = lobalization.CultureInfo.CurrentCulture.NumberFormat.CurrencyDecimalSeparator Then
MyBase.OnKeyPress(e)
Else
e.Handled = True
End If
End Sub
End Class
I suggest that you use regular expressions. You can search Google, like 'regular expression textbox only numeric' and I guess you'll come up with many examples.
For example, if you are in ASP.NET you can do it like:
<asp:TextBox
ID="txtPhoneNumber"
runat="server"
Text='<%#Bind("phoneNumber") %>'
MaxLength="15">
</asp:TextBox>
<asp:RegularExpressionValidator
ID="rfvUSerPhoneNumberValidate"
runat="server"
ControlToValidate="txtPhoneNumber"
Display="Dynamic"
ValidationExpression="^[0-9]{1,15}$"
ErrorMessage="Please enter only numeric value for Phone Number"
EnableViewState="true">
</asp:RegularExpressionValidator>
This will allow numeric input ,Backspace to correct your input , and also a decimal point.
If (e.KeyChar < "0" OrElse e.KeyChar > "9") AndAlso e.KeyChar <> ControlChars.Back AndAlso e.KeyChar <> ControlChars.Cr AndAlso e.KeyChar <> "." Then
Beep()
e.Handled = True
End If
This is another way to restrict number inputs into textbox . using KEYPRESS Events
If Asc(e.KeyChar) <> 13 AndAlso Asc(e.KeyChar) <> 8 AndAlso Not IsNumeric(e.KeyChar) Then
MessageBox.Show("Only Numbers")
e.Handled = True
End If
End Sub
hope it helps ! thnks ..
The purpose of your function could help provide additional solutions. Checking for a numeric value on each KeyPress is likely overkill. Then you have to overkill it more by accounting for backspace, delete, copy, paste, etc.
For example, if you are storing a telephone number, you should use the "IsNumeric" function on the validate and update step. Alternatively, if you are selecting quantity of an item "NumericUpDown" control would be more appropriate than a TextBox.