我收到此错误(FileName.exe 中发生类型 'System.IndexOutOfRangeException' 的未处理异常)- 它由写入行函数发生
I get this error (An unhandled exception of type 'System.IndexOutOfRangeException' occurred in FileName.exe ) - it occurs by the write line function
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
单个方法中发生的事情太多了。将您的代码划分为具有单一目的的方法可以帮助您专注于该目的。我将代码分解为验证、读取、写入和清除。这大大简化了按钮代码。
可以使用 TryParse
方法和 String.IsNullOrEmpty
改进验证代码,但我没有管它。
在读取代码中,我使用了 List(Of T)
来累加值。这不需要您提供初始大小或使用 ReDim Preserve
添加数据。
intLoop
的唯一原因是在您的消息框中显示错误行的索引。
Write 代码在 For 循环中使用列表。我假设你的意思是用空的 For 循环来包围对文件的写入。我不明白你为什么要添加除了列表中的数字之外所有相同数据的记录。如果这是你想要的,那么在循环外解析连接一次,然后将数字添加到循环中的字符串。
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
抱歉,我没有机会测试此代码,所以可能会出现一些错误。如果您从文本文件中提供了一些示例数据,那会更容易。
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
单个方法中发生的事情太多了。将您的代码划分为具有单一目的的方法可以帮助您专注于该目的。我将代码分解为验证、读取、写入和清除。这大大简化了按钮代码。
可以使用 TryParse
方法和 String.IsNullOrEmpty
改进验证代码,但我没有管它。
在读取代码中,我使用了 List(Of T)
来累加值。这不需要您提供初始大小或使用 ReDim Preserve
添加数据。
intLoop
的唯一原因是在您的消息框中显示错误行的索引。
Write 代码在 For 循环中使用列表。我假设你的意思是用空的 For 循环来包围对文件的写入。我不明白你为什么要添加除了列表中的数字之外所有相同数据的记录。如果这是你想要的,那么在循环外解析连接一次,然后将数字添加到循环中的字符串。
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
抱歉,我没有机会测试此代码,所以可能会出现一些错误。如果您从文本文件中提供了一些示例数据,那会更容易。