In vb.net, how do I force validating controls within a (winform) datarepeater after the data is populated? - vb.net

I have a form with a datarepeater that contains various controls (i.e. datetimepickers, text boxes, combo box) that are populated via a binding source. I also have other controls on the form that are not part of the data repeater.
I would like to force validating all controls after the data is populated. I have successfully forced validating the non-datarepeater controls using Me.ValidateChildren() at the end of my load event. However, it does not fire the validating events for the controls within the data repeater.
I have unsuccessfully tried many different attempts to set and move focus within the datarepeater controls trying to get the validating events kicked off. I am not sure where would be the best place (e.g. in drawItem? in ItemCloned?) to place the code and what it should be exactly. Here was my latest attempt:
Private Sub DataRepeater1_DrawItem(ByVal sender As Object, ByVal e As Microsoft.VisualBasic.PowerPacks.DataRepeaterItemEventArgs) _
Handles DataRepeater1.DrawItem
For i = 0 To e.DataRepeaterItem.Controls.Count - 1
e.DataRepeaterItem.Controls.Item(i).Focus()
e.DataRepeaterItem.Controls.Item(0).Focus()
Next
Note: I successfully handled the validating events in the data repeater caused by user input errors. However, I have the unusual situation that the data coming into my form is already bad for some of the controls. The purpose of the form is to validate the data coming in to it and from user-input.
Thanks in advance for any help. I am newbie with vb.net.

Have you tried calling
DataRepeater1.ValidateChildren()
after calling form's Me.ValidateChildren()
MSDN link
EDIT:
Can you try this
Private Shared Function ValidateAllChildern(cc As ContainerControl) As Boolean
Return cc.ValidateChildren() And cc.Controls.OfType(Of ContainerControl)().[Select](Function(c) ValidateAllChildern(c)).Aggregate(True, Function(x, y) x And y)
End Function
and call
ValidateAllChildren(Me)

Here is what I ended up using and it worked great. Basically, you can call the same validation functions in cellformatting and cellvalidating. Cell formatting handles the validation on initial load. Cell validating handles validation on user changes. Also, if you want a global change on user entry (e.g. change to upper case), use EditControlShowing.
A nice feature too is that it shows the little error icon in the cell the error occurred on. Here are the details, fyi.
'handles dgv validation on initial load
Private Sub dgvExample_CellFormatting(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellFormattingEventArgs) _
Handles dgvExample.CellFormatting
Dim results As String = ""
If e.RowIndex <> -1 Then
Select Case e.ColumnIndex
Case 1, 2 'starting and ending service dates
results = ValidateDate(e.Value)
If results = "" Then
results = ValidateDateRange(e.RowIndex)
End If
Case 11 'billed amount
results = ValidateBilledAmount(e.RowIndex)
End Select
dgvExample.Rows(e.RowIndex).Cells(e.ColumnIndex).ErrorText = results
End If
End Sub
'handles dgv validation from user changes
Private Sub dgvExample_CellValidating(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellValidatingEventArgs) _
Handles dgvExample.CellValidating
Dim results As String = String.Empty
dgvExample.CurrentCell.ErrorText = String.Empty
Select Case dgvExample.Columns(e.ColumnIndex).HeaderText
Case "Start Date", "End Date"
results = ValidateDate(e.FormattedValue)
If results = "" Then
results = ValidateDateRange(e.RowIndex)
End If
Case "Billed Amt"
dgvExample(e.ColumnIndex, e.RowIndex).Value = FormatNumber(CType(e.FormattedValue, Double), 2, TriState.False, TriState.False, TriState.False).ToString
results = ValidateBilledAmount(e.RowIndex)
End Select
dgvExample.CurrentCell.ErrorText = results
End Sub
'handles dgv dataentry events
Private Sub dgvExample_EditingControlShowing(ByVal sender As Object, _
ByVal e As System.Windows.Forms.DataGridViewEditingControlShowingEventArgs) _
Handles dgvExample.EditingControlShowing
'Change Case to upper case for all textboxes
Dim editingControl As TextBox = TryCast(e.Control, TextBox)
If editingControl IsNot Nothing Then
editingControl.CharacterCasing = CharacterCasing.Upper
End If
End Sub
'FUNCTIONS called in above
'check dates not old or in future
Private Function ValidateDate(ByVal dte As String) As String
Dim errorMessage As String = ""
If CType(dte, Date) > Now Then
errorMessage = "DATE cannot be in the future"
Return errorMessage
End If
If CType(dte, Date) <= Now.Date.AddYears(-1) Then
errorMessage = "WARNING: DATE cannot be older than 1 year"
Return errorMessage
End If
Return errorMessage
End Function
'Checks that start date is less than end date
Private Function ValidateDateRange(ByVal rowIndex As Integer) As String
Dim errorMessage As String = ""
If CType(dgvExample.Rows(rowIndex).Cells(1).Value, Date) > _
CType(dgvExample.Rows(rowIndex).Cells(2).Value, Date) Then
errorMessage = "START DATE cannot be after END DATE"
End If
Return errorMessage
End Function
'validates billed amount is currency and in range
Private Function ValidateBilledAmount(ByVal rowIndex As Integer) As String
Dim errorMessage As String = ""
Dim billedAmt = dgvExample.Rows(rowIndex).Cells(11).Value
If Not String.IsNullOrEmpty(billedAmt) Then
If IsNumeric(billedAmt) Then
If CType(billedAmt, Decimal) > 0 Then
If billedAmt > 100000.0 Then
errorMessage = "BILLED AMOUNT must not exceed $100,000"
End If
Else
errorMessage = "BILLED AMOUNT must be greater than $0"
End If
Else
errorMessage = "BILLED AMOUNT must be numeric"
End If
End If
If errorMessage = "" Then
CalculateNewTotal()
End If
Return errorMessage
End Function

I just tested this and in order to get the ValidateChildren to work, you need to programmatically set the event handler using AddHandler.
Private Sub DataRepeater1_DrawItem(ByVal sender As Object, ByVal e As Microsoft.VisualBasic.PowerPacks.DataRepeaterItemEventArgs) _ Handles DataRepeater1.DrawItem
AddHandler e.DataRepeaterItem.Controls.Item("ctlDateTimePicker").Validated, AddressOf dtpStartingServiceDate_Validating ' Validating DatePicker
AddHandler e.DataRepeaterItem.Controls.Item("ctlComboBox").Validated, AddressOf cboUnitType_Validating
End Sub
Once the Validated event handler is initialized, you can then call 'Me.ValidateChildren()' to cause the validation to run. I don't know if it's good or bad for your situation but the validation event will execute whenever the control's value is changed.
Let me know if that works.

Related

Data doesn't display when working with multiple forms

I'm new to VB.NET and have been struggling all afternoon with something. I've found similar questions on the forum but none of them seemed to describe my problem exactly. I'm fairly sure that I'm missing something very basic.
I have made a main form which currently holds only one button which purpose is to open up a second form and close the main form. Based on the settings the user will select on the 2nd form the first form might have to be adapted to match with the new settings. But the problem occurs even before that.
The 'settings' form has 15 textboxes which I drew onto the form in development mode. They are called ID1, ID2,..,ID15. The values which I want to display in there are saved in an array:
Dim ids(15) as integer
Next, I created a module to simulate what you could call a control array as I used to use them in VB6.
Public sources() As TextBox = [frmSettings.ID1, frmSettings.ID2, //and so on
I did this to be able to iterate through all the 15 textboxes:
For i = 0 To 14
Sources(i).Text = ids(i + 1)
Next
Then I added on the main form this code to the Button1_Click() event:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
frmSettings.Show()
Me.Close()
End Sub
I did the same thing for the 'exit ' button on the frmSettings form.
This seems to work, but only once. I launch the application, push the button and frmSettings pops up and shows all the values from the array in the textboxes. When I push the 'close' button, I return to the main page.
So far so good, but if I try to return to frmSettings a second time, all the textboxes remain blank as if the code I added to the form never gets executed.
Any help would be greatly appreciated!
First, make sure the array that holds your data is accessible to both forms:
Module Module1
Public ids(15) As Integer
End Module
There should not be a declaration for "ids" in either form.
Next, make frmSettings itself responsible for loading and saving the data:
Public Class frmSettings
Private Sub frmSettings_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim matches() As Control
For i As Integer = 0 To 14
matches = Me.Controls.Find("ID" & (i + 1), True)
If matches.Length > 0 AndAlso TypeOf matches(0) Is TextBox Then
Dim TB As TextBox = DirectCast(matches(0), TextBox)
TB.Text = ids(i)
End If
Next
End Sub
Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
Dim valid As Boolean = True
Dim matches() As Control
For i As Integer = 0 To 14
matches = Me.Controls.Find("ID" & (i + 1), True)
If matches.Length > 0 AndAlso TypeOf matches(0) Is TextBox Then
Dim TB As TextBox = DirectCast(matches(0), TextBox)
Dim value As Integer
If Integer.TryParse(TB.Text, value) Then
ids(i) = value
Else
MessageBox.Show(TB.Name & ": " & TB.Text, "Invalid Value", MessageBoxButtons.OK, MessageBoxIcon.Warning)
valid = False
End If
End If
Next
If valid Then
Me.Close()
End If
End Sub
End Class

Form Control Validation for User Input in (VB.NET 2005)

I am writing an application for my Notary business. I am a Notary Public in Iowa.
I have many types of control on the form. ComboBox (that can be modified), TextBox and MaskedTextBox.
I know I can use the TextBoxBase class to cover the TextBox and also the MaskedTextBox, but my validation code is not doing anything. Nothing happens.
I have an ErrorProvider on the form called ErrorProvider. It has the "AutoValidate" option set to "EnableAllowFocusChange". The BlinkStyle is set to AlwaysBlink. All other properties are default.
I have three buttons on the form, too. Reset, Save and Close. Both the Reset and Close buttons are set to CausesValidation = False and the Save button is set to CausesValidation = True.
I need to make sure the "required" fields have a value when the Save button is clicked.
So, I figured I would use the Validated and Validating events of the controls. But, when clicking Save, nothing happens. The ErrorProvider doesnt even show. If I leave the control empty, still nothing happens.
This is my code:
Private Sub Company_Validated(ByVal sender As Object, ByVal e As System.EventArgs) _
Handles Company.Validated, CompanyAddress.Validated, CompanyCity.Validated, CompanyZipCode.Validated, CompanyPhone.Validated, CompanyAddressRemit.Validated, CompanyCityRemit.Validated, CompanyZipCodeRemit.Validated
ErrorProvider.SetError(CType(sender, TextBoxBase), String.Empty)
End Sub
Private Sub Company_Validating(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) _
Handles Company.Validating, CompanyAddress.Validating, CompanyCity.Validating, CompanyZipCode.Validating, CompanyPhone.Validating, CompanyAddressRemit.Validating, CompanyCityRemit.Validating, CompanyZipCodeRemit.Validating
Dim ErrorMessage As String = String.Empty
Dim TheField As TextBoxBase = CType(sender, TextBoxBase)
If TypeOf TheField Is MaskedTextBox Then
CType(TheField, MaskedTextBox).TextMaskFormat = MaskFormat.ExcludePromptAndLiterals
End If
If Not IsValid(TheField, ErrorMessage) Then
e.Cancel = True
TheField.Select(0, TheField.Text.Length)
ErrorProvider.SetError(TheField, ErrorMessage)
End If
End Sub
Private Function IsValid(ByVal ControlName As TextBoxBase, ByVal ErrorMessage As String) As Boolean
If String.IsNullOrEmpty(ControlName.Text.ToString) Then
ErrorMessage = "This is a required field."
Return False
Else
ErrorMessage = String.Empty
Return True
End If
End Function
Any ideas on what I am doing wrong?
The String class in vb.net is a bit "odd". It's a reference type that acts (not all cases) like a value type. You need to change ByVal to ByRef.
Private Function IsValid(ByVal ControlName As TextBoxBase, ByRef ErrorMessage As String) As Boolean

Passing arguments to methods in VB

I'm hoping you guys can help with a problem that should be simple to solve, I've just had issues finding a solution. In the program that I'm writing some of the textbox's have to be numeric between 1 and 10, and others just have to be numeric. Instead of coding each textbox to verify these parameters I decided to write methods for each of them. I'm having problems passing the arguments and getting it to function correctly. Included is some of my code that shows what I'm trying to accomplish.
Public Shared Sub checkforonetoten(ByVal onetoten As Double)
If (onetoten > 1 & onetoten < 10) Then
Else
MessageBox.Show("Please enter a Number between 1-10", "Error")
End If
End Sub
Public Shared Sub checkfornumber(numCheck As Double)
Dim numericCheck As Boolean
numericCheck = IsNumeric(numCheck)
If (numericCheck = False) Then
MessageBox.Show("Please enter a number", "Error")
End If
End Sub
Private Sub textboxS_TextChanged(sender As Object, e As EventArgs) Handles textboxS.TextChanged
Dim S As Double
S = textboxS.Text
checkfornumber(S)
checkforonetoten(S)
End Sub
One of your main problems is you're converting your text without validating it. You're also programming without the Options On to warn you of bad conversion techniques like you're using in the event handler.
The TryParse method would come in handy here:
Private Sub textboxS_TextChanged(sender As Object, e As EventArgs) Handles textboxS.TextChanged
Dim S As Double
If Double.TryParse(textboxS.Text, S) Then
checkforonetoten(S)
End If
End Sub
Since the TryParse method validates your text and sets the value to 'S', you only need to check the range.
Of course using NumericUpDown controls would make all this moot, since the values will always only be numbers and you can set the range on each one.
one way to structure it is to have one event procedure process the similar TB types:
Private Sub textboxS_TextChanged(sender As Object, e As EventArgs) _
Handles textbox1.TextChanged, textbox12.TextChanged, _
Handles textbox16.TextChanged
Dim S As Double
If Double.TryParse(Ctype(sender, TextBox).Text, S) Then
' or place the Check code here for all the TextBoxes listed above
checkforonetoten(S)
End If
End Sub
The plain numeric kind:
Private Sub textboxQ_TextChanged(sender As Object, e As EventArgs) _
Handles textbox2.TextChanged, textbox6.TextChanged
Dim S As Double
If Double.TryParse(Ctype(sender, TextBox).Text, S) = False Then
MessageBox.Show("Please enter a number", "Error")
End If
End Sub
Rather than calling a function and passing the current TextBox from events (which is fine), have 2 or 3 events process them all. The point is adding/moving the Handles clause to a common event procedure (be sure to delete the old ones).
If you do decide to call a common function, dont do anything in the events (you still have one per TB) and do it all in the common proc:
Private Sub textboxS_TextChanged(sender As Object, e As EventArgs) _
Handles textboxS.TextChanged
checkforonetoten(Sender)
End Sub
private Sub checkforonetoten(tb As Textbox)
Dim S As Double
If Double.TryParse(tb.Text, S) Then
' your check for 1 - 10 on var S
else
' error: not a valid number
End If
end sub
Also:
If (onetoten > 1 & onetoten < 10) Then
should be:
If (onetoten > 1) AndAlso (onetoten < 10) Then

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