Вопрос

I wanted to trap this condition that when a user input a letter in the contact number textbox it will show a message box and it will say "That is not a valid contact number" here is my code

Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
        con.Open()
        If MsgBox("Are you sure you want to save changes?", vbYesNo) = MsgBoxResult.Yes Then

            Dim cmd As New SqlCommand("Insert Into pInformation (palName,pafName,pamName,pabirthdate,paaddress,panumber) Values (@lname,@fname,@mname,@birthdate,@address,@number)", con)
            cmd.Parameters.AddWithValue("lname", TextBox1.Text)
            cmd.Parameters.AddWithValue("fname", TextBox2.Text)
            cmd.Parameters.AddWithValue("mname", TextBox3.Text)
            cmd.Parameters.AddWithValue("birthdate", DateTimePicker1.Value.Date)
            cmd.Parameters.AddWithValue("address", TextBox4.Text)
            cmd.Parameters.AddWithValue("number", TextBox6.Text)
            cmd.ExecuteNonQuery()
            con.Close()
            Me.PInformationTableAdapter.Fill(Me.JoshuadbDataSet1.pInformation)
            MessageBox.Show("Record successfully added.")
        ElseIf MsgBox("Are you sure you want to save this?", vbYesNo) = MsgBoxResult.No Then
            con.Close()
        End If
        TextBox1.Clear()
        TextBox2.Clear()
        TextBox3.Clear()
        TextBox4.Clear()
        TextBox6.Clear()
    End Sub
Это было полезно?

Решение

In order to validate if the contents of TextBox6 are a valid number you can use the Integer.TryParse method.

Dim number As Integer
If Not Integer.TryParse(TextBox6.Text, number) Then
  MessageBox.Show("Not a number")
  Return
End If 

Другие советы

You should validate the contact number in your code and provide a message rather than sending it to the db to fail and catching the error. Don't use Try Catch to do validation that you can do through normal means.

Edit:

How you should validate the number depends entirely on what range of numbers you accept. Are you validating numbers purely on looking like genuine numbers? If so you may want to use a Regular Expression. Eg...

Dim num As String=TextBox6.Text
'Regex to allow only numbers 
Dim rex As Regex=New Regex("^[0-9]+$")
If Not rex.IsMatch(num) Then
    'Alert user of bad number and do not execute SQL call

If you actually need to validate the number against numbers already in the database then obviously a call to the database will be necessary, and there is an argument here for using Try Catch and having your database call throw an error signifying the exact problem.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top