Dim outputFile As IO.Path
Dim filepath As String = "PCPT2Database.txt"
'Append a new Entry into PCPT2Database
Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
'Declare variables
Dim newNo As Integer = 0
Dim NewEmail As String = 0
Dim NewSurname As String = 0
Dim NewName As String = 0
Dim NewCell As Integer = 0
'Defencive Programming
If txtName.Text = "" Or IsNumeric(txtName.Text) Then
MessageBox.Show("Please enter a Valid Name")
txtName.Focus()
Else : NewName = txtName.Text
End If
If txtSurname.Text = "" Or IsNumeric(txtSurname.Text) Then
MessageBox.Show("Please enter a Valid Surname")
txtSurname.Focus()
Else : NewSurname = txtSurname.Text
End If
If txtEmail.Text = "" Or IsNumeric(txtEmail.Text) Then
MessageBox.Show("Please enter a Valid Email")
txtEmail.Focus()
Else : NewEmail = txtEmail.Text
End If
If mtbCell.Text = "" Then
MessageBox.Show("Please enter a 10 digit number")
mtbCell.Focus()
End If
Dim filePath As String = "T2Database.txt"
Dim intNewNo() As Integer = {}
Dim intCount As Integer = 0
Dim currentRow() As String
Dim intLoop As Integer
Using MyReader As New Microsoft.VisualBasic.FileIO.TextFieldParser(filePath)
MyReader.TextFieldType = FileIO.FieldType.Delimited
MyReader.SetDelimiters(",")
While Not MyReader.EndOfData
Try
currentRow = MyReader.ReadFields()
ReDim Preserve intNewNo(intCount)
intNewNo(intCount) = currentRow(0)
intCount = +1
Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
MsgBox("line" & ex.Message & " Its not valid.")
End Try
End While
End Using
For intLoop = 0 To intCount + 1
Next
If IO.File.Exists(filePath) Then
Using outputFile = IO.File.AppendText(filePath)
outputFile.WriteLine**(Join({intNewNo(intLoop).ToString, txtName.Text, txtSurname.Text, mtbCell.Text, txtEmail.Text}, ","))**
End Using
MessageBox.Show("Save Successful")
MessageBox.Show("Add another record", "Cancel", MessageBoxButtons.OKCancel, MessageBoxIcon.Information)
txtName.Clear()
txtSurname.Clear()
mtbCell.Clear()
txtEmail.Clear()
Else
MessageBox.Show(filePath, ".txt not found.",
MessageBoxButtons.RetryCancel, MessageBoxIcon.Information)
End If
End Sub
-
1Does this answer your question? [What is an IndexOutOfRangeException / ArgumentOutOfRangeException and how do I fix it?](https://stackoverflow.com/questions/20940979/what-is-an-indexoutofrangeexception-argumentoutofrangeexception-and-how-do-i-f) – David Sep 17 '20 at 17:59
-
`intCount = +1`: you probably meant `intCount += 1`. Did you check whether `intNewNo` has something in it (did you debug this code)? Try to use `List
` instead of arrays there. Is the empty loop supposed to do something meaningful, in relation to what comes after? – Jimi Sep 17 '20 at 18:03 -
changing int count to intcount = +1 did help,THANK YOU. – AtumDC Sep 17 '20 at 18:14
-
1Right at the top of your code 3 out 5 of the `'Declare Variables` are wrong. Please turn on Option Strict. This is a 2 part process. First for the current project - In Solution Explorer double click My Project. Choose Compile on the left. In the Option Strict drop-down select ON. Second for future projects - Go to the Tools Menu -> Options -> Projects and Solutions -> VB Defaults. In the Option Strict drop-down select ON. This will save you from bugs at runtime. – Mary Sep 17 '20 at 18:20
-
What is the empty For loop supposed to do? `For intLoop = 0 To intCount + 1` ? – Mary Sep 17 '20 at 19:21
-
To declare a new entry number. – AtumDC Sep 17 '20 at 21:04
1 Answers
There is way too much going on in a single method. Dividing your code into methods with a single purpose helps you concentrate on that purpose. I broke the code into Validate, Read, Write, and Clear. This greatly simplifies the button code.
The validating code could be improved with TryParse
methods and String.IsNullOrEmpty
but I left it alone.
In the Read code I used a List(Of T)
to accumulate the values. This does not require you to provide an initial size or use ReDim Preserve
to add data.
The only reason for intLoop
is to display the index of an errant line in your message box.
The Write code uses the list in the For loop. I assumed that you meant the empty For loop to surround the writing to the file. I do not understand why you want to add records with all the same data except the number form the list. If this is what you want then resolve the join once outside the loop and then just add the number to the string in the loop.
Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
If Not IsInputValid() Then
Exit Sub
End If
Dim filePath As String = "T2Database.txt"
Dim intNewNo = ReadInputFile(filePath)
If AppendToDataFile(intNewNo) Then
MessageBox.Show("Save Successful")
ClearTextBoxes()
Else
MessageBox.Show($"{filePath} not found.", "Save Failed", MessageBoxButtons.OK, MessageBoxIcon.Information)
End If
End Sub
Private Function IsInputValid() As Boolean
If txtName.Text = "" Or IsNumeric(txtName.Text) Then
MessageBox.Show("Please enter a Valid Name")
txtName.Focus()
Return False
End If
If txtSurname.Text = "" Or IsNumeric(txtSurname.Text) Then
MessageBox.Show("Please enter a Valid Surname")
txtSurname.Focus()
Return False
End If
If txtEmail.Text = "" Or IsNumeric(txtEmail.Text) Then
MessageBox.Show("Please enter a Valid Email")
txtEmail.Focus()
Return False
End If
If mtbCell.Text = "" Then
MessageBox.Show("Please enter a 10 digit number")
mtbCell.Focus()
Return False
End If
Return True
End Function
Private Function ReadInputFile(FullFilePath As String) As List(Of Integer)
Dim filePath As String = "T2Database.txt"
Dim lst As New List(Of Integer)
Dim intLoop As Integer = 0
Dim lines = File.ReadAllLines(filepath)
Dim NewNum As Integer
For Each line In lines
If Integer.TryParse(line.Substring(0, line.IndexOf(","c)), NewNum) Then
lst.Add(NewNum)
Else
MessageBox.Show($"Line Num {intLoop} containing{line} is not valid.")
End If
intLoop += 1
Next
Return lst
End Function
Private Function AppendToDataFile(intNewNo As List(Of Integer)) As Boolean
Dim filepath As String = "PCPT2Database.txt"
If IO.File.Exists(filepath) Then
Using outputFile = File.AppendText(filepath)
For Each number In intNewNo
outputFile.WriteLine(Join({number.ToString, txtName.Text, txtSurname.Text, mtbCell.Text, txtEmail.Text}, ","))
Next
End Using
Return True
Else
Return False
End If
End Function
Private Sub ClearTextBoxes()
txtName.Clear()
txtSurname.Clear()
mtbCell.Clear()
txtEmail.Clear()
End Sub
I am sorry, I didn't have an opportunity to test this code so expect some bugs. It would have been easier if you had provided a bit of sample data from the text file.

- 14,926
- 3
- 18
- 27