validating alphanumeric input in textbox [VB2010] - vb.net

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

Related

How can I essentially stop my VB program until a valid value is entered via Text Box?

How can I work around an invalid/null value entered into a text box?
Basically I have a simple program I need to develop to solve a simple quadratic equation:
Public Class Main
Private Sub btnHelp_Click(sender As System.Object, e As System.EventArgs) Handles btnHelp.Click
UserGD.Show()
End Sub
Private Sub btnClear_Click(sender As System.Object, e As System.EventArgs) Handles btnClear.Click
txtStepX.Text = ""
lstResult.Items.Clear()
End Sub
Private Sub cmdGo_Click(sender As System.Object, e As System.EventArgs) Handles cmdGo.Click
Do
txtStepX.Text = InputBox("Please enter a valid value for x!", "Oops!", "")
Loop While String.IsNullOrEmpty(txtStepX.Text)
Dim stepx As Single
Dim X As Single
Dim y As Single
stepx = txtStepX.Text
Dim result As String
For X = -5 To 5 Step stepx
y = (3 * (X) ^ 2) + 4
result = ("x = " & X & " >>>>>>>>>> y = " & y)
lstResult.Items.Add(result)
Next
End Sub
End Class
This is the part I want to focus on:
Do
txtStepX.Text = InputBox("Please enter a valid value for x!", "Oops!", "")
Loop While String.IsNullOrEmpty(txtStepX.Text)
Dim stepx As Single
Dim X As Single
Dim y As Single
stepx = txtStepX.Text
Dim result As String
The above manages to check the text box (after its text value is changed by the Input Box) and loops fine, as long as it is empty... However, say I put a letter in, say, "l", it crashes and Visual Studio gives me the error "Conversion from string 'l' to type 'Single' is not valid." - which is fair enough. Although, I assumed the Null in isNullorEmpty meant it would catch invalid values, such as strings when it's supposed to be single.
I've tried quite a few things, and even my Computing teacher has been trying to get a solution.
I can't remember most of the things I've tried thus far so if I'll give whatever you guys come up with a go just to be on the safe side!
Update
Although not the clearest of code - here is what I found works the best for my needs:
'Written by a very tired and frustrated Conner Whiteside
'With his own blood.
'And sweat.
'And tears.
'Lots of tears.
'28/10/2014
Public Class Main
Private Sub btnHelp_Click(sender As System.Object, e As System.EventArgs) Handles btnHelp.Click
UserGD.Show()
End Sub
Private Sub btnClear_Click(sender As System.Object, e As System.EventArgs) Handles btnClear.Click
txtStepX.Text = ""
lstResult.Items.Clear()
End Sub
' On Go button click
Private Sub cmdGo_Click(sender As System.Object, e As System.EventArgs) Handles cmdGo.Click
'Checks if Text Box value is a number
If IsNumeric(txtStepX.Text) Then
'Declares variables if Text Box value is in fact a number
Dim result As String
Dim stepx As Double
Dim X As Double
Dim y As Double
'Displays error message with a re-input opportunity if previously entered number is out of range.
Do While txtStepX.Text <= 0 Or txtStepX.Text > 10
'InputBox simply changed the value of the TextBox's Text. MUST be an InputBox or there will be nothing to break the loop.
txtStepX.Text = InputBox("The step size for the x values must not be a negative number or above 10." & vbCrLf & "Please enter another number for the step size of the x values.", "Oops!")
'Covers an Empty input given that IsNumeric does not. This can also prevent crashing if the 'Cancel' or 'X' is pressed on InputBox.
If txtStepX.Text = "" Then
'Exits Sub Class in order to avoid running mathematical operations (below) with a string "". Effectively allows a 'reset'.
Exit Sub
End If
Loop
'After all checks, sets Text Boxvalue to variable stepx
stepx = txtStepX.Text
'Loops the solving of the equation from x = -5 to x = 5 with the specified step size.
For X = -5 To 5 Step stepx
'sets the answer of the equation (y) to variable y.
y = (3 * (X) ^ 2) + 4
'concatenates a string in the required format.
result = ("x = " & X & " >>>>>>>>>> y = " & y)
'Adds the result to the List Box before repeating the process for the next value of x.
lstResult.Items.Add(result)
Next
'Catches any non numeric inputs in the Text Box or the Input Box e.g "l".
ElseIf Not IsNumeric(txtStepX.Text) Then
'Displays error message before ending If statement and Sub Class, allowing the user to return to the start and try another input. - No Input Box or Exit Sub needed.
MsgBox("Please enter a valid number for the step size of the values of x.", 64, "Oops!")
End If
End Sub
End Class
Honestly wouldn't have gotten anywhere if it weren't for your efforts!
I would simply check if the input is numeric.
If IsNumeric(txtStepX.text) then
// Your statements
Else
// MsgBox("Please enter a number")
End if
However, it will accept something like 3.5.4
A more complicated solution would be to limit the characters from being entered by checking on each keypress,
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
//Statements here
Else
e.Handled = True
End If
End If
End Sub
First, I recommend that you use the Double type instead of Single - it won't make any difference to how fast your program runs, but it will reduce rounding errors a lot.
Second, you can use Double.TryParse to check if a string can be parsed as a Double value. IsNumeric has some quirks which you do not want to find out about.
I took the liberty of adjusting the text which is shown to the user, as an "Oops!" before they have even tried to enter a value might be confusing, and it is better to tell them a number is needed than "a valid value":
Dim stepx As Double
Dim inp As String = ""
Dim inputTitle As String = "Number required"
Do
inp = InputBox("Please enter a number for x:", inputTitle)
' change the input box title to indicate something is wrong - if it is shown again.
inputTitle = "Oops!"
Loop While Not Double.TryParse(inp, stepx)
txtStepX.Text = stepx.ToString()

If else inside a loop in VB.Net

The code below shows the event when a button click is fire
Protected Sub btnFinish_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnFinish.Click
For i As Integer = 0 To Gridview1.Rows.Count - 1 Step i + 1
Dim TextBox1 As TextBox = DirectCast(Me.Gridview1.Rows(i).FindControl("txtAnswer"), TextBox)
If TextBox1.Text = String.Empty Then
'do something
ElseIf TexBox1 <> String.Empty Then
'do something else
End If
Next
End Sub
The problem here is that the only condition being executed is in the If-statement even if it should execute the ElseIf-statement. Can someone explain why and how can I solve this problem? [EDITED]
a couple of things to note when comparing text/string:
String could be NULL, instead of Empty
use String.IsNULLOrEmpty to check NULL/Empty
String could be WhiteSpace too, use String.IsWhiteSpace to check it
User could enter a few spaces in some cases, if you want to make sure it's correct, use String.Trim to eliminate any unwanted spaces.
normally what I do is: (NOT String.IsNULLOrEmpty(givenText)) AndAlso givenText.Trim.Length <> 0

Variables to list box?

taking a VB class this term and I've been stumped on a problem I'm trying to figure out. We were asked to create a price calculator for movie titles at a movie rental place. Extra credit was storing them in a list and being able to print the list. I've gotten that far and now I want to go a step further and actually add titles to that list with an attached price. I figured the easiest way to do this would probably be with arrays but I don't have much experience working with arrays.
I was thinking something along the lines of storing each title(as its added) as well as the price in a variable to give a "Movie Title - $2.93" format in every line of the list box. For the sake of this problem I'm going to just post my full source code and that might make it easier to see what I'm trying to accomplish. ANY help would be MUCH appreciated. Thanks Stack overflow community!
A screenshot of my project can be viewed here: http://puu.sh/54SgI.jpg
Public Class Form1
'globablly declared because I might use them outside of btnAdd_Click event
Const decDiscount As Double = 0.9 '1-.10 discount = .9
Const decDVD As Decimal = 2D
Const decBlueray As Decimal = 2.5D
Const decDVDNew As Decimal = 3.25D
Const decBluerayNew As Decimal = 3.5D
Dim intCount As Integer
Dim decCost, decTotal As Decimal
Dim decDayTotal As Decimal
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
AcceptButton = btnAdd
End Sub
Private Sub chkDiscount_Click(sender As Object, e As EventArgs) Handles chkDiscount.Click
If chkDiscount.CheckState = 1 Then
chkDiscount.Enabled = False
End If
End Sub
Private Sub btnAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAdd.Click
'Display error when no title entered
If txtAdd.Text = "" Then
MessageBox.Show("Please enter a movie title and select the appropriate item details.", "Complete details", MessageBoxButtons.OK, MessageBoxIcon.Error)
Else
listMovies.Items.Add(txtAdd.Text)
listMovies.SelectedIndex = listMovies.SelectedIndex + 1
End If
'update list
'clear txtbox
txtAdd.Text = ""
'Decision Statements to calculate correct price
If radDVD.Checked = True Then
decCost = CDec(decDVD.ToString("c"))
If chkNew.Checked = True Then
decCost = CDec(decDVDNew.ToString("c"))
End If
ElseIf radBlueray.Checked = True Then
decCost = CDec(decBlueray.ToString("c"))
If chkNew.Checked = True Then
decCost = CDec(decBlueray.ToString("c"))
End If
End If
If chkDiscount.Checked = True Then
decCost = CDec((decCost * decDiscount).ToString("c"))
End If
'display cost
txtCost.Text = CStr(CDec(decCost))
'calc total
decTotal = CDec(decTotal + decCost)
'display total
txtTotal.Text = CStr(CDec(decTotal))
'clear chkNew every item added to list
chkNew.CheckState = 0
End Sub
'Public so summary message box can access variable
Public Sub btnFinish_Click(sender As Object, e As EventArgs) Handles btnFinish.Click
'Add +1 to counter & update txtCounter
intCount = CInt(Val(intCount) + 1)
'add to day total
decDayTotal = CDec(Val(decDayTotal) + decTotal)
'Set Everything back to empty/enabled
chkDiscount.Enabled = True
chkDiscount.CheckState = 0
chkNew.CheckState = 0
txtAdd.Text = ""
txtCost.Text = ""
txtTotal.Text = ""
decTotal = 0
decCost = 0
'Instead of clearing radios each time, a more desirable result would be to have DVD always set back to the default checked radio
radDVD.Checked = True
radBlueray.Checked = False
listMovies.Items.Clear()
End Sub
Private Sub btnSummary_Click(sender As Object, e As EventArgs) Handles btnSummary.Click
If decTotal > 0 Then
MessageBox.Show("Please finish your current order before viewing a daily summary.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
Else
MessageBox.Show(("Your total cutomer count is: " & intCount) + Environment.NewLine + ("Your total sales today is: $" & decDayTotal), "Daily Summary", MessageBoxButtons.OK)
End If
End Sub
Private Sub btnRemove_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnRemove.Click
listMovies.Items.Remove(listMovies.SelectedItem)
End Sub
I wont go very far here because you need to do the work. But, I would start with a class:
Public Class Movie
Public Title As String = ""
Public Cost As Decimal
' prevents you from adding a movie without critical info
Public Sub New(ByVal t As String, ByVal c As Decimal)
Title = t
Cost = c
End Sub
End Class
This would hold the info on one movie title rental, and keep it together (and can be added to in order to print exactly as you showed) . The plan (to the extent I understand what you are after) would be to create one of these for each movie rented and add it to a List(Of Movie) this is more appropriate than a Dictionary in this case.
To create a movie:
Dim m As New Movie(theTitle, theCost)
Things I would do:
You did a good job of declaring numerics as numbers. Fix the code that converts it to string and back to numeric. (edit your post)
You can use the Movie Class to populate the "Shopping Cart" listbox alone; at which point, listMovies.Items would BE the extra credit List. But it wouldnt hurt to use/learn about List (Of T). (BTW, does 'print' mean to paper, on a printer?)
What are you doing with chkDiscount? If they check it, you disable it (and never enable). Did you mean to disable the New Releases check? In THAT case, arent they really a pair of radios too?
Either way, CheckChanged is a better event for evaluating and there is no reason to manually set the check state for the user that happens by itself.
Check out List(of T) and HTH
A good thing to think about when doing assignments like this (particularly when learning your first language) is to think of the algorithm (the step you need to get to your goal).
1st, determine all the steps you need to get to your goal.
2nd, and I think this is the more import point for your question, figure out what order the steps need to be in (or better yet, what order they are most efficient in).
In your case I think that you are kind of ice skating up hill by adding the name of the movie to the list first, and then trying to add the price to the line later. Unless that kind of functionality was requested as part of the assignment I would require the user to enter both the name AND the price before accepting either (just like you do with the name currently). Like thus:
If txtAdd.Text <> "" AND txtCost.Text <> "" Then 'requiring both fields to not be null
''add moive code
Else
''MessageBox.Show("Yadda Yadda Yadda")
End If
I agree with Plutonix that creating a class, while overkill in your case, is a good idea, as it will give you practice for when it WILL be appropriate. Once you have that a class of Movie, you can then create lists of Movie(s) like this:
Dim MovieList as new List(of Movie)
So then, each time you press the btnAdd button, you can pass the values to a movie AND add it to the list.
Dim m As Movie
Dim MovieList as new List(of Movie)
Private Sub btnAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAdd.Click
'Display error when no title entered
If txtAdd.Text <> "" And txtCost.Text <> "" Then
myMovie = New Movie(txtAdd.Text, txtCost.Text)
myMovieList.Add(myMovie)
listMovies.Items.Clear()
For Each X As Movie In myMovieList
listMovies.Items.Add(X.DisplayMovie)
Next
Else
MessageBox.Show("Please enter a movie title and select the appropriate item details.", "Complete details", MessageBoxButtons.OK, MessageBoxIcon.Error)
End If
'Other Code
End Sub
Note the line ListMovies.Items.Add(X.DisplayMovie) I added a function to the class Movie (seen below) so that it will do the formatting as you suggested.
Public Function DisplayMovie()
Return Title & " - $" & Cost
End Function
This will get you much of the way. Try to extrapolate what Plutonix and myself have explained to further refine your code. For instance, try encapsulating your adjusted price calculation in its own function so you can call it from anywhere.

Comparing a datetimepicker with a string

i'm pretty new into coding and visual basic. Today I was assigned to complete a program that i'm having some trouble with. I need to develop an app that allows the user to enter the appointment and the time it needs to be competed, however i need to implement an error check to make sure no two times are the same, this is where i'm running into problems. I'm unsure how i can compare a datetimepicker.value to the listbox text. I'm getting the Conversion from string "" to type Date is not valid error. Any help is much appreciated!
Public Class Form1
Function TimeTaken() As Boolean
Dim app As String = TextBox1.Text
Dim timeofapp As String = DateTimePicker1.Value.ToShortTimeString
If CDate(ListBox2.Text) = CDate(DateTimePicker1.Value) Then
MsgBox("Two appointments are scheduled within the same time frame.", MsgBoxStyle.Exclamation)
TimeTaken = True
Else
TimeTaken = False
ListBox1.Items.Add(app)
ListBox2.Items.Add(timeofapp)
TextBox1.Text = ""
End If
End Function
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
TimeTaken()
End Sub
End Class
"I'm unsure how i can compare a datetimepicker.value to the listbox text"
You need to iterate over all the values stored in the ListBox.Items() property:
Function TimeTaken() As Boolean
Dim AlreadyTaken As Boolean = False ' assume not taken until proven otherwise below
Dim app As String = TextBox1.Text
Dim timeofapp As String = DateTimePicker1.Value.ToShortTimeString
For Each time As String In ListBox2.Items
If time = timeofapp Then
MsgBox("Two appointments are scheduled within the same time frame.", MsgBoxStyle.Exclamation)
AlreadyTaken = True
Exit For
End If
Next
If Not AlreadyTaken Then
ListBox1.Items.Add(app)
ListBox2.Items.Add(timeofapp)
TextBox1.Text = ""
End If
Return AlreadyTaken
End Function

Text box validation

I am using many text boxes in a form.
How do i validate them,
In certain text boxes I have to use only text and in some I have to use only numbers.
Is using ASCII is a right method or is there any easier method to do this. If so please let me know the coding.
Above all other, don’t annoy the user. If I’m typing some text and the application prevents that (regardless of how it does that), I’m rightfully pissed off.
There are multiple values to handle this:
Use a NumericUpDown or a Slider control instead of a text box for numeric values (in other words: use the correct control instead of a general-purpose control).
Allow (more or less) arbitrary input and try to parse the user input in a meaningful way. For example, entering “+33 (0) 6 12-34-56” is an entirely meaningful format for a phone number in France. An application should allow that, and try to parse it correctly.
Granted, this is the hardest way, but it provides the best user experience.
Use the Validating event to validate input. This is automatically triggered whenever the user leaves the input control, i.e. when they have finished their input, and a validation will not annoy the user.
The MSDN documentation of the event gives an example of how this event is used correctly.
But do not use the KeyPress or TextChanged events to do validation. The first will disturb the users when entering text. The second will also annoy them when they try to paste text from somewhere else. Imagine the following: I am trying to copy an number from a website. Unfortunately, the text I have copied includes something else, too, e.g. “eggs: 14.33 EUR” instead of just “14.33”.
Now, the application must give me the chance to paste and correct the text. If I am not allowed to do that, the application is a UX failure. If the application uses the TextChanged event to prevent my pasting this text, I don’t get the chance to delete the offending text.
Text only limited to 40 characters:
<asp:RegularExpressionValidator ID="regexpText" runat="server"
ErrorMessage="Text only!"
ControlToValidate="txtName"
ValidationExpression="^[a-zA-Z]{1,40}$" />
Only Numbers:
<asp:RegularExpressionValidator ID="regexpNumber" runat="server"
ErrorMessage="Numbers only!"
ControlToValidate="txtName"
ValidationExpression="^[0-9]$" />
Wow, this can be a very broad topic...
For numeric textboxes, you should probably restrict input during KeyPress event:
Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
Dim allowedChars As String = "0123456789"
If allowedChars.IndexOf(e.KeyChar) = -1 Then
' Invalid Character
e.Handled = True
End If
End Sub
NOTE: This code sample is assuming WinForms, different approach must be used for web...
Regardless of the plat form, you should look into the validation controls offered by the framework, and that will allow you to validate that there is indeed input, values are in a specified range, and also using regex write more complicated validation rules.
The fastest way for validation is using regular expressions. They are harder to understand but offer better performance.
But you could do it also using string functions. Which is easier if you don't know regex but is less performant. This could be a viable option, depending on how hard the validation is.
Here and here are some posts that will help you with code samples.
Agreed that Regular Expressions might be faster, but ... well, here's how I've done it. Basically, this code is for a UserControl which contains a label, a text box, and an error provider. It also has various other properties, but here's the bit which deals with validation.
I do use this on the TextChanged event, because I don't want the user to continue typing if it's an invalid character; the rule checking "eats" the invalid character.
Public Enum CheckType
ctString = 0
ctReal = 1
ctDecimal = 2
ctInteger = 3
ctByte = 4
End Enum
Private mAllowNegative As Boolean = True
Private mAllowNull As Boolean = True
Private mCheckType As CheckType = CheckType.ctString
<System.Diagnostics.DebuggerStepThrough()> _
Private Sub TextBox1_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged
RuleCheckMe()
End Sub
<System.Diagnostics.DebuggerStepThrough()> _
Private Sub RuleCheckMe()
'// Rule Checking
If Me.TextBox1.TextLength = 0 Then
If mAllowNull = False Then
Me.epMain.SetError(Me.TextBox1, "You are required to provide this value.")
Me.Valid = False
Else
Me.epMain.Clear()
Me.Valid = True
End If
Else
Select Case mCheckType
Case CheckType.ctString
If mInputMask.Length > 0 Then
'TODO: Figure out how to cope with input masks!
Me.Valid = True
Else
Me.Valid = True
End If
Case Else '// right now we're only testing for numbers...
If Not IsNumeric(Me.TextBox1.Text) And Me.TextBox1.Text <> "." And Me.TextBox1.Text <> "-" Then
If Not String.IsNullOrEmpty(Me.TextBox1.Text) Then
Me.TextBox1.Text = Me.TextBox1.Text.Remove(Me.TextBox1.Text.Length - 1, 1)
Me.TextBox1.SelectionStart = Me.TextBox1.Text.Length
End If
Me.epMain.SetError(Me.TextBox1, "This field does not accept non-numeric values.")
Me.Valid = False
ElseIf mAllowNegative = False And Me.TextBox1.Text.StartsWith("-") Then
Me.TextBox1.Text = Me.TextBox1.Text.Remove(Me.TextBox1.Text.Length - 1, 1)
Me.epMain.SetError(Me.TextBox1, "This field does not accept negative values.")
Me.Valid = False
ElseIf mCheckType = CheckType.ctByte And CType(Me.TextBox1.Text, Integer) > 255 Then
Me.epMain.SetError(Me.TextBox1, "This field does not accept values greater than 255.")
Me.Valid = False
Else
Me.epMain.Clear()
Me.Valid = True
End If
End Select
End If
End Sub
<System.ComponentModel.Browsable(True), _
System.ComponentModel.DesignerSerializationVisibility(System.ComponentModel.DesignerSerializationVisibility.Visible), _
System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always), _
System.ComponentModel.Category("Data")> _
Public Property AllowNegative() As Boolean
<System.Diagnostics.DebuggerStepThrough()> _
Get
Return mAllowNegative
End Get
<System.Diagnostics.DebuggerStepThrough()> _
Set(ByVal value As Boolean)
mAllowNegative = value
End Set
End Property
<System.ComponentModel.Browsable(True), _
System.ComponentModel.DesignerSerializationVisibility(System.ComponentModel.DesignerSerializationVisibility.Visible), _
System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always), _
System.ComponentModel.Category("Data")> _
Public Property AllowNull() As Boolean
<System.Diagnostics.DebuggerStepThrough()> _
Get
Return mAllowNull
End Get
<System.Diagnostics.DebuggerStepThrough()> _
Set(ByVal value As Boolean)
mAllowNull = value
End Set
End Property
<System.ComponentModel.Browsable(True), _
System.ComponentModel.DesignerSerializationVisibility(System.ComponentModel.DesignerSerializationVisibility.Visible), _
System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always), _
System.ComponentModel.Category("Data")> _
Public Property DataTypeCheck() As CheckType
<System.Diagnostics.DebuggerStepThrough()> _
Get
Return mCheckType
End Get
<System.Diagnostics.DebuggerStepThrough()> _
Set(ByVal value As CheckType)
mCheckType = value
End Set
End Property
i would like to share my text box validator..
Dim errProvider As New ErrorProvider
' Verify that this field is not blank.
Private Sub txtValidating(sender As Object,
e As System.ComponentModel.CancelEventArgs) Handles _
txtName.Validating, txtStreet.Validating, txtCity.Validating,
txtState.Validating, txtZip.Validating
' Convert sender into a TextBox.
Dim txt As TextBox = DirectCast(sender, TextBox)
' See if it’s blank.
If (txt.Text.Length > 0) Then
' It’s not blank. Clear any error.
errProvider.SetError(txt, “”)
Else
' It’s blank. Show an error.
errProvider.SetError(txt, “This field is required.”)
End If
End Sub
' See if any field is blank.
Private Sub Form1_FormClosing(sender As Object,
e As FormClosingEventArgs) Handles Me.FormClosing
If (txtName.Text.Length = 0) Then e.Cancel = True
If (txtStreet.Text.Length = 0) Then e.Cancel = True
If (txtCity.Text.Length = 0) Then e.Cancel = True
If (txtState.Text.Length = 0) Then e.Cancel = True
If (txtZip.Text.Length = 0) Then e.Cancel = True
End Sub
Private Sub TxtEmployeenumber_KeyPress(sender As Object, e As KeyPressEventArgs) Handles TxtEmployeenumber.KeyPress
Dim c As Char
c = e.KeyChar
If Not (Char.IsDigit(c) Or c = "." Or Char.IsControl(c)) Then
e.Handled = True
MsgBox("numeric texts only")
End If
End Sub
just go to the keyup event of text box and enter the following code
100% it will work
if(Not Char.IsNumber(Chrw(e.Keycode))) Then
Messagebox.show ("only numeric values ")
textbox1.text=""
end if