Validation set in access breaks the program - vb.net

The program breaks and displays this message once I input the wrong amount of numbers in a textbox and submited the form.
An unhandled exception of type 'System.Data.OleDb.OleDbException'
occurred in System.Data.dll
Additional information: One or more values are prohibited by the
validation rule 'Is Null Or Like "###########"' set for
'T_Jobs.Customer_Phone'. Enter a value that the expression for this
field can accept."
I have connected visual basic to access using the data source connecting wizard. I want the program to display a message saying "input 11 numbers" instead of it breaking.

You can create a validation function
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If IsValidForm() Then
' Save the Record
' This line takes all the input from the boxes from adding a New job form, And puts it into
' corresponding boxes in the main menu = because only those boxes
' are connected to the database
' It uses the data adapter from form1
Form1.T_JobsTableAdapter.Insert(Me.TextBox2.Text, M, e.TextBox3.Text, Me.TextBox4.Text,
Me.TextBox5.Text, Me.TextBox6.Text, Me.TextBox7.Text, Me.TextBox8.Text)
'This line updates the table Jobs dataset with the information in the boxes in main menu
'The DataSet passes on the collected data to the database
Form1.T_JobsTableAdapter.Fill(Form1.JobsDBDataSet.T_Jobs)
MsgBox("Record added successfully")
' These lines clear the textboxes so that next job can be added
TextBox2.Text = ""
TextBox3.Text = ""
TextBox4.Text = ""
TextBox5.Text = ""
TextBox6.Text = ""
TextBox7.Text = ""
TextBox8.Text = ""
End If
End Sub
Private Function IsValidForm() As Boolean
Dim msg As String = String.Empty
' Ensure that a Valid Vehicle Model was entered
If TextBox3.Text = "" Then
' MsgBox("Please fill in Car Model", MsgBoxStyle.Information)
msg += "Enter a Car Model" & vbCr
End If
' Validate Date Received
If Not IsDate(TextBox2.Text) Then
msg += "Enter a valid Date Received" & vbCr
End If
' Validate Date Due
If Not IsDate(TextBox2.Text) Then
msg += "Enter a valid Date Due" & vbCr
End If
' Validate Phone Number
If Trim(TextBox8.Text) = "" Then
' NOTE I am not sure how you want to validate this phone number.
' You can do it with RegEx
' The Regular Expression tells VB to make sure that TextBox8 contains only
' Numbers 1 - 9 and only a length of 11. If it does not match, then
' display the validation message
If Not System.Text.RegularExpressions.Regex.IsMatch(TextBox8.Text, "^[0-9]{11}$") Then
msg += "Enter a Phone Number" & vbCr
End If
End If
If msg.Length > 0 Then
MessageBox.Show("Please fix the following errors before continuing:" & Microsoft.VisualBasic.ControlChars.CrLf & msg,
Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Information)
Return False
Else
Return True
End If
End Function

this is the code for adding data, it also validates if a textbox isnt empty and if the date is in date format
If TextBox3.Text = "" Then
MsgBox("Please fill in Car Model", MsgBoxStyle.Information)
Else
'This checks if the Date Recieved and Date Due is in the correct format
If IsDate(TextBox2.Text) And IsDate(TextBox6.Text) Then
'This line takes all the input from the boxes from adding a new job form, and puts it into
'corresponding boxes in the main menu = because only those boxes
'are connected to the database
'It uses the data adapter from form1
Form1.T_JobsTableAdapter.Insert(Me.TextBox2.Text, Me.TextBox3.Text, Me.TextBox4.Text,
Me.TextBox5.Text, Me.TextBox6.Text, Me.TextBox7.Text, Me.TextBox8.Text)
'This line updates the table Jobs dataset with the information in the boxes in main menu
'The dataset passes on the collected data to the database
Form1.T_JobsTableAdapter.Fill(Form1.JobsDBDataSet.T_Jobs)
MsgBox("Record added sucessfully")
'These lines clear the textboxes so that next job can be added
TextBox2.Text = ""
TextBox3.Text = ""
TextBox4.Text = ""
TextBox5.Text = ""
TextBox6.Text = ""
TextBox7.Text = ""
TextBox8.Text = ""
Else
MsgBox("Please ensure the Date Recieved and Date Due is in dd/mm/yyyy format", MsgBoxStyle.Information)
End If
End If

Related

Checks The Informations In Text File. VB.NET

I work on a project "SignInLogeIn" using Visual Basic.NET.
I save the user informations in text file.
the name of the file is "data.txt".
to create a new account in my program. you must enter the name,email,password and the program write the informations in textfile.
i use "Streamwritter" to write the informations.
when user create a new account The program checks if the email entered by the user is already in the text file that contains the users' information.
and the program checks from informations by "StreamReader". it reads the information in text file and checks.
I have the problem.
when I CREATE A new account. problem appears.
and the problem is
"
An unhandled exception of type 'System.IO.IOException' occurred in mscorlib.dll
Additional information: The process cannot access the file 'D:\1- Anas Files\Projects\VisualBasic.NET\SignInLogIn\SignInLogIn\SignInLogIn\bin\Debug\Data.txt' because it is being used by another process.
"
I think the problem is that I used the file twice
Once to write and once to read.
The error occurs in this line "Dim sw As New StreamWriter("Data.txt")".
how can i solve this problem ?
this is the code of "SignIn" button
Private Sub btnSignIn_Click(sender As Object, e As EventArgs) Handles btnSignIn.Click
Dim strEmail As String = txtEmail.Text
Dim Reg As New Regex("^\w+([-_.]\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*$")
If txtUserName.Text.Trim() = "" Or txtEmail.Text.Trim() = "" Or txtPassword.Text.Trim() = "" Then
MsgBox("Please Enter All Input")
If Not Reg.IsMatch(strEmail) Then
MsgBox("Please Enter Email")
End If
Else
Dim sr As New StreamReader("Data.txt")
Dim sw As New StreamWriter("Data.txt")
Dim strPerson As String = txtUserName.Text & ";" & txtEmail.Text & ";" & txtPassword.Text
Dim line As String = ""
Do
line = sr.ReadLine()
Dim arrData As String() = line.Split(";")
If arrData(1) = strEmail Then
MsgBox("Please Change Email")
Else
sw.WriteLine(strPerson)
sw.Close()
End If
Loop While line <> Nothing
sr.Close()
End If
End Sub
You open twice the same file. First, to read and second to write, this is why you cannot write.
Dim sr As New StreamReader("Data.txt")
Dim lines As String = sr.ReadToEnd().Split(Environment.NewLine)
sr.Close()
Dim strPerson As String = txtUserName.Text & ";" & txtEmail.Text & ";" & txtPassword.Text
Dim sw As New StreamWriter("Data.txt")
For Each line As String In lines
Dim arrData As String() = line.Split(";")
If arrData(1) = strEmail Then
MsgBox("Please Change Email")
Exit For
Else
sw.WriteLine(strPerson)
Exit For
End If
Next
sw.Close()
Streams need to be closed and disposed. They are usually put in Using blocks.
I wasn't quite sure of the program flow you wanted. It seemed, since you created a writer and a reader you intended to add to user to the file if they were not listed.
I broke out some of the code into separate methods. I used System.IO since we have a simple text file.
Private Sub btnSignIn_Click(sender As Object, e As EventArgs) Handles btnSignIn.Click
If ValidInput() Then
Dim strPerson As String = $"{txtUserName.Text};{txtEmail.Text};{txtPassword.Text}"
If Not IsUserInFile(strPerson) Then
File.AppendAllText("Data.txt", strPerson & Environment.NewLine)
End If
End If
End Sub
Private Function ValidInput() As Boolean
Dim strEmail As String = txtEmail.Text
Dim Reg As New Regex("^\w+([-_.]\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*$")
If txtUserName.Text.Trim() = "" OrElse txtEmail.Text.Trim() = "" OrElse txtPassword.Text.Trim() = "" Then
MsgBox("Please Enter All Input")
Return False
If Not Reg.IsMatch(strEmail) Then
MsgBox("Please Enter Email")
Return False
End If
End If
Return True
End Function
Private Function IsUserInFile(Person As String) As Boolean
Dim p = Person.Split(";"c)
Dim lines = File.ReadAllLines("Data.txt")
For Each line In lines
If Person = line Then
Return True
End If
Dim fields = line.Split(";"c)
If fields(0) = p(0) AndAlso fields(2) = p(2) AndAlso fields(1) <> p(1) Then
MessageBox.Show("Please Change Email")
Return False
End If
Next
Return False
End Function
This is going to get messy and slow if there are too many users. This info should really be in a database. The worst thing is the passwords should always be salted and hashed; never stored as plain text even is a database.

DataGridView selected row index

Why is the dgView.CurrentCell.RowIndex always 0? I need to know which row and column a user is trying to edit. column 1 can only be edited if it is a new row. column 4 can be edited only if it is not a new row. No other columns can be edited.
I need to be able to add a new row.
I've tried .CellBeginEdit with e as DataGridViewCellCancelEventArgs
And no, I don't want to bind my data to the SQL table. I need to make sure the user knows they are changing the data when they save it.
I've tried with CellMouseClick and CellMouseLeeave with disastrous results. I found these two and thought I had them working but testing proves that not to be the case.
My code (some of which is redundant as I'm still trying to understand what events I should be working with):
Private Sub dgTools_CellBeginEdit(sender As Object, e As DataGridViewCellCancelEventArgs) Handles dgTools.CellBeginEdit
Dim i As Integer
With dgTools
i = .CurrentCell.RowIndex
Select Case e.ColumnIndex
Case 1
If .CurrentCell.RowIndex < .NewRowIndex Then
Dim msg As Object, hdr As Object
msg = "You may not edit the tool ID"
hdr = "Edit Error"
MsgBox(msg, MsgBoxStyle.Critical, hdr)
End If
Case 4
originalValue = .CurrentCell.Value
End Select
.EndEdit()
End With
End Sub
Private Sub dgTools_CellEndEdit(sender As Object, e As DataGridViewCellEventArgs) Handles dgTools.CellEndEdit
Dim dtCheck As New DataTable
Dim hdr As Object, msg As Object
With dgTools
.EndEdit()
Select Case e.ColumnIndex
Case 1
Select Case originalValue
Case ""
.CurrentCell.Value = UCase(.CurrentCell.Value)
dtCheck = GetDataTable("GetTool_x_BrochsteinsID", "#BrochsteinsID", .CurrentCell.Value)
' Brochsteins ID is not a valid ID
If dtCheck.Rows.Count = 0 Then
hdr = "Invalid Brochsteins ID"
msg = "Entry is not a valid Brochsteins ID." & vbCrLf & "Please enter a valid ID."
MsgBox(msg, MsgBoxStyle.Critical, hdr)
.Rows.RemoveAt(e.RowIndex)
Exit Sub
End If
' Check that Brochsteins ID is not already assigned to a toolbox
If dtCheck.Rows(0)("Toolstatus") > 1 Then
hdr = "Illegal Brochsteins ID Assignment"
msg = dtCheck.Rows(0)("BrochsteinsID") & " is already assigned to " & dtCheck.Rows(0)("ToolboxDesc") & vbCrLf &
"Please enter a different Brochsteins ID or Return this ID to the Tool Room first."
MsgBox(msg, MsgBoxStyle.Critical, hdr)
.Rows.RemoveAt(e.RowIndex)
Exit Sub
End If
.CurrentRow.Cells(0).Value = dtCheck.Rows(0)("ToolId")
.CurrentRow.Cells(2).Value = dtCheck.Rows(0)("ModelDesc").ToString
.CurrentRow.Cells(3).Value = dtCheck.Rows(0)("CategoryDesc").ToString
.CurrentRow.Cells(4).Value = dtCheck.Rows(0)("AssignedNote").ToString
Case Else
If originalValue <> .CurrentCell.Value Then
hdr = "Edit Brochsteins ID"
msg = "You may not edit a Brochsteins ID." & vbCrLf & "You may only Delete and/or Add a new Brochsteins ID."
MsgBox(msg, MsgBoxStyle.Critical, hdr)
.CurrentCell.Value = originalValue
Exit Sub
End If
End Select
End Select
Dim Note As String
If Not IsDBNull(.CurrentRow.Cells("AssignedNote").Value) Then Note = .CurrentRow.Cells("AssignedNote").Value Else Note = ""
UpdateTool_Toolbox(.CurrentRow.Cells("ToolID").Value, cboToolbox.SelectedValue, Note)
If dtCheck IsNot Nothing Then dtCheck.Dispose()
dgTools.EndEdit()
QueryTable("Tools")
QueryTable("Standard")
End With
End Sub

Struggling with basic VB.net. Variable addition

I'm trying to set up my form program so if the user fails to login 3 times (linked to a database), it closes the program. However, I'm a kinda crap at programming and I can't get the variable to actually hold the addition I'm trying to use?
Private Sub Login_Click(sender As Object, e As EventArgs) Handles Login.Click
Dim uname, pass As String
Dim attempt As Integer = 0
' Warns the user if they have missed out login information.
If UserNameBox.Text = "" Or PasswordBox.Text = "" Then
MessageBox.Show("Please ensure you have entered your username and password", "Authentication Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
Else
uname = UserNameBox.Text
pass = PasswordBox.Text
GetFilteredData("username = '" & uname & "' AND password = '" & pass & "'")
If CountRecords() = 1 Then
MsgBox("Logged In!")
Else
MsgBox("Incorrect Credentials!")
attempt = attempt + 1 ' <-- Main Issue is here
If attempt = 4 Then
Application.Exit()
End If
End If
End If
End Sub
Any help would be amazing. Thanks :D
You're declaring on the attempt varible inside the Login_Click event handler. Hence, each time the Login_Click event is raised, you are initializing it to 0.
Dim attempt As Integer = 0
Try to move it to outer scope, for example make it a member of the Class.
This should work. If you want to have variable accessible from all subs, just take it out too root of class.
Private attempt As Integer = 0
Private Sub Login_Click(sender As Object, e As EventArgs) Handles Login.Click
Dim uname, pass As String
' Warns the user if they have missed out login information.
If UserNameBox.Text = "" Or PasswordBox.Text = "" Then
MessageBox.Show("Please ensure you have entered your username and password", "Authentication Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
Else
uname = UserNameBox.Text
pass = PasswordBox.Text
GetFilteredData("username = '" & uname & "' AND password = '" & pass & "'")
If CountRecords() = 1 Then
MsgBox("Logged In!")
Else
MsgBox("Incorrect Credentials!")
attempt = attempt + 1 ' <-- Main Issue is here
If attempt = 4 Then
Application.Exit()
End If
End If
End If
End Sub

Login with textboxes in visual basic, 3 tries

I'm making a login script in VB using textboxes.
My problem is that the msgbox which inform the user about attempts left keep looping itself as well and using up all the (3) tries.
Not sure what's wrong.
here is my code:
Dim cor_pw As String = "1234"
Dim cor_us As String = "abcd"
Dim tries1 As Integer = 3
tries1 -= 1
Do
MsgBox("wrong combination, " & tries1 & " chances left to make it right.")
Loop Until textbox1.Text = cor_us And textbox2.Text = cor_pw Or tries1<= 0
If textbox1.Text = cor_us And textbox2.Text = cor_pw Then
MsgBox("Congratulations! That's Correct!")
Else
MsgBox("You've used all tries! " & tries1 & " chances left, good bye!")
Me.Close()
End If
You need an OK button that indicates the user has finished entering text.
In the event for the OK button you would
validate the text
If valid then you are good
otherwise increment the retry1 variable -- which must be declared at the Form (module) level!
now test retry1
if retry 1 is > 3 then display failure message and disable the OK button
otherwise display retry message
exit the sub
At this point the user can reenter the values and then hit OK button again.
No loop.
Your loop event is in the wrong area(s)
Dim cor_pw As String = "1234"
Dim cor_us As String = "abcd"
Dim tries1 As Integer = 3
Do Until (textbox1.Text = cor_us And textbox2.Text = cor_pw) Or tries1<= 0
If textbox1.Text = cor_us And textbox2.Text = cor_pw Then
MsgBox("Congratulations! That's Correct!")
Else
MsgBox("You've used all tries! " & tries1 & " chances left, good bye!")
Me.Close()
End If
MsgBox("wrong combination, " & tries1 & " chances left to make it right.")
tries1 -= 1
Loop

How to use timer in vb.net

I have this code:
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
Dim num As String
Dim message As String
Dim name As String
message = txtMessage.Text
Dim count As Integer = Me.TblContactsBindingSource.Count
If i < TblContactsDataGridView.Rows.Count - 1 Then 'stay within bounds
i = i + 1 ' for all rows except Row0
TblContactsDataGridView.Rows(i - 1).DefaultCellStyle.BackColor = Color.White ' restore previous highlight
TblContactsDataGridView.Rows(i).DefaultCellStyle.BackColor = Color.Bisque 'new highlight
num = Me.TblContactsDataGridView.Rows(i).Cells(1).Value.ToString()
name = Me.TblContactsDataGridView.Rows(i).Cells(0).Value.ToString()
If SerialPort1.IsOpen() Then
SerialPort1.Write("AT" & vbCrLf)
SerialPort1.Write("AT+CMGF=1" & vbCrLf)
SerialPort1.Write("AT+CMGS=" & Chr(34) & num & Chr(34) & vbCrLf)
SerialPort1.Write(message & Chr(26))
MessageBox.Show("Message has been successfully sent to " & vbNewLine & name & " (" & num & ") ", "Message Sent", MessageBoxButtons.OK, MessageBoxIcon.Information)
End If
Else 'next row is off the bottom so
'i = 0 'reset index
'TblSmsDataGridView.Rows(TblSmsDataGridView.Rows.Count - 1).DefaultCellStyle.BackColor = Color.White 'restore bottom row
'TblSmsDataGridView.Rows(i).DefaultCellStyle.BackColor = Color.Bisque 'highlight top row
End If
In a command button I have this:
Timer1.Interval = 2000
Timer1.Enabled = True 'no need to enable it and start it; one or t'other
What happen is, the message box appears over and over. How can i trigger message box to automatically close once it is finished? I commented the code in the "else" because the it repeats over and over.
You have to use a custom message box. Normal message box wont do the thing you wanted. It will pop up every 2 second. best choice is to make a new form and show it as a message box. :)
You need to set timer1.enabled = false in the timer1.tick handler.