Visual Basic:TRY\CATCH exception handling issues - vb.net

I am working on an employee database and am having issues with my TRY\CATCH for saving records as it pertains to exception handling. The issue I am experiencing is that it will run the TRY and ignore the CATCH, allowing invalid data to pass and save to the file. I am very new to visual basic and am unsure of why this is not working. Here is my code for the form:
Option Strict Off
Imports System.IO
Public Class frmEmployeeData
'Variable Declarations
Dim BlnisChanged As Boolean = False
Dim empFirstName As String
Dim empMiddleName As String
Dim empLastName As String
Dim empNumber As Integer
Dim empDepartment As String
Dim empTelephone As String
Dim empExtension As Integer
Dim empEmailAddress As String
Dim empSelection As String
Dim fileName As String
Dim intTryParse As Integer = 0
Private Sub frmEmployeeData_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'Adds the department options to the combo box dropdown list
ComboBoxEmpDepartment.Items.Add("Accounting")
ComboBoxEmpDepartment.Items.Add("Administration")
ComboBoxEmpDepartment.Items.Add("Marketing")
ComboBoxEmpDepartment.Items.Add("MIS")
ComboBoxEmpDepartment.Items.Add("Sales")
End Sub
Sub ClearItems()
'Clears text boxes
txtFirstName.Clear()
txtMiddleName.Clear()
txtLastName.Clear()
txtEmployeeNumber.Clear()
ComboBoxEmpDepartment.ResetText()
txtTelephone.Clear()
txtExtension.Clear()
txtEmailAddress.Clear()
End Sub
Sub SaveItems()
Dim savedEmployeeFile As StreamWriter
Try
'Creates the employee file
savedEmployeeFile = File.CreateText(fileName)
'writes information entered by user into file
savedEmployeeFile.WriteLine(txtFirstName.Text)
savedEmployeeFile.WriteLine(txtMiddleName.Text)
savedEmployeeFile.WriteLine(txtLastName.Text)
savedEmployeeFile.WriteLine(txtEmployeeNumber.Text)
savedEmployeeFile.WriteLine(ComboBoxEmpDepartment.Text)
savedEmployeeFile.WriteLine(txtTelephone.Text)
savedEmployeeFile.WriteLine(txtExtension.Text)
savedEmployeeFile.WriteLine(txtEmailAddress.Text)
'Closes the file
savedEmployeeFile.Close()
BlnisChanged = False
'Clears the text boxes
ClearItems()
Catch ex As Exception
'Throws error if file could Not be created
MessageBox.Show("Unable To Create File. Please Try Again", "Error In Saving")
End Try
End Sub
Sub AppendToFile()
Dim savedEmployeeFile As StreamWriter
Try
'append to file
savedEmployeeFile = File.AppendText(fileName)
'writes information entered by user into file
savedEmployeeFile.WriteLine(txtFirstName.Text)
savedEmployeeFile.WriteLine(txtMiddleName.Text)
savedEmployeeFile.WriteLine(txtLastName.Text)
savedEmployeeFile.WriteLine(txtEmployeeNumber.Text)
savedEmployeeFile.WriteLine(ComboBoxEmpDepartment.Text)
savedEmployeeFile.WriteLine(txtTelephone.Text)
savedEmployeeFile.WriteLine(txtExtension.Text)
savedEmployeeFile.WriteLine(txtEmailAddress.Text)
MessageBox.Show("Employee saved successfully.", "Success")
'Closes the file
savedEmployeeFile.Close()
BlnisChanged = False
'Clears the text boxes
ClearItems()
Catch ex As Exception
MessageBox.Show("No file exists. Please select 'Save As' Option.", "Error In Saving")
End Try
End Sub
Private Sub btnSaveRecord_Click(sender As Object, e As EventArgs) Handles btnSaveRecord.Click
Dim savedEmployeeFile As StreamWriter
'EXCEPTION HANDLING
'verifies first name field content
If txtFirstName.Text = "" Then
MessageBox.Show("First name cannot be blank", "Invalid Entry")
End If
'verifies middle name field content
If txtMiddleName.Text = "" Then
MessageBox.Show("Middle name cannot be blank", "Invalid Entry")
End If
'verifies last name field content
If txtLastName.Text = "" Then
MessageBox.Show("Last name cannot be blank", "Invalid Entry")
End If
'verifies employee number field content
If txtEmployeeNumber.Text = "" Then
MessageBox.Show("Employee number cannot be blank", "Invalid Entry")
ElseIf Not (Integer.TryParse(txtEmployeeNumber.Text, intTryParse)) Then
MessageBox.Show("Employee number must be numeric", "Invalid Entry")
ElseIf CStr(txtEmployeeNumber.Text) < 0 Then
MessageBox.Show("Employee number must be positive", "Invalid Entry")
End If
'verifies department field content
If ComboBoxEmpDepartment.Text = "" Then
MessageBox.Show("Employee department cannot be blank", "Invalid Entry")
End If
'verifies telephone number field content
If txtTelephone.Text = "" Then
MessageBox.Show("Telephone number cannot be blank", "Invalid Entry")
ElseIf Not (Integer.TryParse(txtEmployeeNumber.Text, intTryParse)) Then
MessageBox.Show("Telephone number must be numeric", "Invalid Entry")
End If
'verifies extension field content
If txtExtension.Text = "" Then
MessageBox.Show("Extension cannot be blank", "Invalid Entry")
ElseIf Not (Integer.TryParse(txtExtension.Text, intTryParse)) Then
MessageBox.Show("Extension must be numeric", "Invalid Entry")
ElseIf CInt(txtExtension.Text) < 0 Then
MessageBox.Show("Extension must be positive", "Invalid Entry")
End If
'verifies email address field content
If txtEmailAddress.Text = "" Then
MessageBox.Show("Email Address cannot be blank", "Invalid Entry")
End If
'If no filename exists, will prompt save dialog box and prompt user to save as
If fileName = String.Empty Then
If sfdSave.ShowDialog = System.Windows.Forms.DialogResult.OK Then
fileName = sfdSave.FileName
SaveItems()
End If
'If filename exists, append item to file
Else
AppendToFile()
End If
End Sub
Private Sub btnClear_Click(sender As Object, e As EventArgs) Handles btnClear.Click
'Clears all content currently within text boxes
txtFirstName.Clear()
txtMiddleName.Clear()
txtLastName.Clear()
txtEmployeeNumber.Clear()
ComboBoxEmpDepartment.ResetText()
txtTelephone.Clear()
txtExtension.Clear()
txtEmailAddress.Clear()
End Sub
Private Sub btnExit_Click(sender As Object, e As EventArgs) Handles btnExit.Click
'Closes Program
frmUserSelection.Show()
Me.Visible = False
End Sub
Private Sub SaveFileDialog1_FileOk(sender As Object, e As System.ComponentModel.CancelEventArgs) Handles sfdSave.FileOk
End Sub
Private Sub PictureBox1_Click(sender As Object, e As EventArgs) Handles PictureBox1.Click
'Picture Obtained From:
'"User Add Icon-Shine Set: Add New User, Add User." Free Icons PNG. Accessed 14 October 2018. https://www.freeiconspng.com/img/2487
End Sub
End Class

A Catch block only executes if an exception is thrown from within the Try block. I don't see anything here which would cause that to happen. It appears as though you're misunderstanding this a bit.
Don't put validation logic in a Catch block. All that should go there is code to handle an exception if one occurs. For example, if the connection to a database fails because the database itself is offline, or if writing to a file fails because the file can't be found/opened.
Put your validation logic before you even make the attempt to save it. If the user input fails validation, don't attempt to save it. Instead, return an error to the user. Only if your custom validation passes would you then begin the Try, write to your data store, and handle an exception if one occurs.

Related

Pass Information between 2 Forms - VB.Net - Winforms

I have 2 Forms in a Product Registration Project
The 1st form has 3 buttons: New | Consult | Change | - that call the 2nd Form where I have a Photo Button.
New Button:
Private Sub tsbNew_Click(sender As Object, e As EventArgs) Handles tsbNew.Click
Try
Using frm As New frm2ndForm
frm.txtPrdCod.Enabled = True
frm.txtPrdCod.Text = ""
frm.ShowDialog()
End Using
tsbRefresh.PerformClick()
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Critical)
End Try
End Sub
Consult Button:
Private Sub tsbConsult_Click(sender As Object, e As EventArgs) Handles tsbConsult.Click
Try
If DGProds.CurrentRow Is Nothing Then
MessageBox.Show("Select one product")
Exit Sub
End If
Using frm As New frm2ndForm
frm.txtPrdCod.Enabled = False
frm.txtPrdCod.Text = DGProds.CurrentRow.Cells("prdCod").Value.ToString.Trim 'dr.Item("prdCod")
frm.txtDes.Enabled = False
frm.txtDesRed.Enabled = False
frm.ShowDialog()
End Using
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Critical)
Exit Sub
End Try
End Sub
Change Button
Private Sub tsbChange_Click(sender As Object, e As EventArgs) Handles tsbChange.Click
Try
If DGProds.CurrentRow Is Nothing Then
MessageBox.Show("Select one product")
Exit Sub
End If
Using frm As New frm2ndForm
frm.txtPrdCod.Enabled = False
frm.txtPrdCod.Text = DGProds.CurrentRow.Cells("prdCod").Value.ToString.Trim 'dr.Item("prdCod")
frm.ShowDialog()
End Using
tsbRefresh.PerformClick()
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Critical)
End Try
End Sub
In the 2nd Form, the Photo button will have two different behaviors:
when the user has clicked on the "New" button on Form 1, the code will open a search screen for the user to select an image in a folder on the Photos in server and show it in the picturebox1 in Form 2;
when the user has clicked on the "Consult" or "Change" button on Form 1, the code will make a comparison between the prdCod field of the Products Table and the filename of the image in the Photos folder and, when found, will show the image in the picturebox1 in Form 2.
If the "clicked button" on form 1 is "New", do the commands below:
Private Sub btnPhoto_Click(sender As Object, e As EventArgs) Handles btnPhoto.Click
Using open As New OpenFileDialog With {
.Title = "Select Photo",
.FileName = "",
.Filter = "Images PNG,JPEG,BMP,JPG|*.png;*.jpeg";*.bmp;*.jpg,
.Multiselect = False}
If open.ShowDialog = DialogResult.OK Then
PictureBox1.Image = Image.FromFile(open.FileName)
End If
End Using
End Sub
If the "clicked button" on form 1 is "Consult or Change", execute the commands below:
Private Sub btnPhoto_Click(sender As Object, e As EventArgs) Handles btnPhoto.Click
Dim IdProduto As String = prdCod ***field Products Table that will be used for the search in the Photos folder
If File.Exists("\\server\cmg\projects\Photos" & IdProduto) Then ***Search the image from the Photos folder on the server
PictureBox1.Image = Image.FromFile("\\server\cmg\projects\Photos" & IdProduto)
End If
End Sub
How do I check which button was clicked on the 1st form to be able to perform the correct Private Sub on the 2nd form?
It worked:
In the first form (frmConsProd), in the New Button code (tsbNew_Click), I include the parameter that will be sent to
the second form (frmCadProd):
Public Class frmConsProd
Private Sub tsbNew_Click(sender As Object, e As EventArgs) Handles tsbNew.Click
Try
Using frm As New frmCadProd("New")
frm.txtPrdCod.Enabled = True
frm.txtPrdCod.Text = ""
frm.ShowDialog()
End Using
tsbRefresh.PerformClick()
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Critical)
End Try
End Sub
End Class
In the second form (frmCadProd) I created a class variable (_operation) and the constructor (Public Sub New) to receive the sent parameter:
Public Class frmCadProd
Dim _operation As String
Public Sub New(operation As String)
InitializeComponente()
Select Case operation.ToLower()
Case "new"
_operation = operation
Case Else
MessageBox.Show("Invalid option!")
Close()
End Select
End Sub
End Class
Thanks to Messrs. #F0r3v3r-A-N00b, #jmcilhinney e #user09938, for the help.

Backgroundworker gives multiple error messages

I have a form with three textboxes in it. In my BackgroundWorker1_DoWork handler I test if any TextBox is empty and launch a MessageBox asking the user to fill in all the TextBoxes. This is done in a Try/Catch block. My problem is two fold. If the TextBoxes aren't filled in the user gets the first MessageBox and then another MessageBox when the Catch exception is thrown...so this would be the second MessageBox the user gets. In my BackGroundWorker1_RunWorkCompleted handler I test if an Exception is thrown. It never acknowledges the error and immediately executes the Else block which will be the third message box the user receives saying "Process complete." The Process Complete should not have been shown.
How do I test if there are any TextBoxes not filled in and if they're not throw 1 MessageBox telling the user to fill in all the TextBoxes? And make my RunWorkerComplete handler acknowledge the ElseIf e.Error IsNot Nothing.
Thank you for your help.
Private Sub BackgroundWorker1_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
BackgroundWorker1.WorkerReportsProgress = True
Try
For Each cntrl As Control In Me.Controls()
If TypeOf cntrl Is TextBox Then
If CType(cntrl, TextBox).Text.Equals(String.Empty) Or (CType(cntrl, TextBox).Text = "") Then
cntrl.BackColor = Color.Yellow
MessageBox.Show("Please enter value in all fields on form" & cntrl.Name.ToString())
cntrl.Focus()
End If
End If
Next
runProgram()
Catch ex As Exception
MessageBox.Show("An error occured while trying to load this application. Please contact Maxine Hammett for assistance " &
vbNewLine & "" & vbNewLine & String.Format("Error: {0}", ex.Message))
End Try
End Sub
Private Sub BackgroundWorker1_RunWorkerCompleted(sender As Object, e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted
If e.Cancelled = True Then
MsgBox(" Operation Cancelled ")
ProgressBar1.Value = 0
ElseIf e.Error IsNot Nothing Then
MsgBox("Error in RunWorkerComplete" & e.Error.Message)
Else
MsgBox(" Process Complete ")
Close()
End If
End Sub
Moved the control checking to the execute button. But now I get errors about the text boxes not having a path (one of the text boxes is a path to folder).
Private Sub btnExecute_Click(sender As Object, e As EventArgs) Handles btnExecute.Click
Dim launchProgram As Boolean = False
While launchProgram = False
For Each cntrl As Control In Me.Controls()
If TypeOf cntrl Is TextBox Then
If CType(cntrl, TextBox).Text.Equals(String.Empty) Or (CType(cntrl, TextBox).Text = "") Then
cntrl.BackColor = Color.Yellow
MessageBox.Show("Please enter value in all fields on form" & cntrl.Name.ToString())
cntrl.Focus()
launchProgram = False
Else
launchProgram = True
End If
End If
Next
End While
If launchProgram = True Then
BackgroundWorker1.RunWorkerAsync()
End If
End Sub
I suggest that you check a single text box a time and show the message if its empty:
Private Sub btnExecute_Click(sender As Object, e As EventArgs) Handles btnExecute.Click
For Each cntrl As TextBox In Controls.OfType(Of TextBox)
If String.IsNullOrEmpty(cntrl.Text) Then
cntrl.BackColor = Color.Yellow
MessageBox.Show("Please enter value in all fields on form" & cntrl.Name.ToString())
cntrl.Focus()
Return
Else
cntrl.BackColor = SystemColors.Window
End If
Next
BackgroundWorker1.RunWorkerAsync()
End Sub
Or maybe concatenate the names of the empty text boxes in the For..Each block if you really need to prompt the user this way:
Private Sub btnExecute_Click(sender As Object, e As EventArgs) Handles btnExecute.Click
Dim sb As New StringBuilder
For Each cntrl As TextBox In Controls.OfType(Of TextBox)
If String.IsNullOrEmpty(cntrl.Text) Then
If sb.Length > 0 Then sb.Append(", ")
sb.Append(cntrl.Name)
cntrl.BackColor = Color.Yellow
Else
cntrl.BackColor = SystemColors.Window
End If
Next
If sb.Length > 0 Then
MessageBox.Show("Please enter value in all fields on form" & sb.ToString())
Controls.OfType(Of TextBox).Where(Function(a) String.IsNullOrEmpty(a.Text)).FirstOrDefault?.Focus()
Return
End If
BackgroundWorker1.RunWorkerAsync()
End Sub
Otherwise, run the worker.
Good luck.

Creating a login/register form

I'm working on a vb form, which allows a person to create an "account". I store the usernames and passwords in two arrays, and extract the information from them. But when I run the program, it comes up with a problem:
"An unhandled exception of type 'System.ArgumentNullException'
occurred in Microsoft.VisualBasic.dll, Additional information: Value
cannot be null."
where the code for the Button2/Register Button is (To be exact:
For i = 0 To (UBound(Usernames))
Could you help me out and tell me what to do differently/how to approach this situation? Here is the code:
Public Class Form1
Dim Usernames() As String
Dim Passwords() As String
Dim CurrName As String
Dim i As Integer
'Login button is pressed
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim Index As Integer
CurrName = TextBox1.Text
For i = 0 To (UBound(Usernames))
If IfRepetition(Usernames, CurrName, i) = True Then
Index = Array.IndexOf(Usernames, TextBox1.Text)
If TextBox2.Text = Passwords(Index) Then
Form3.Show()
Me.Hide()
End If
Else
MsgBox("The username or password is incorrect", MsgBoxStyle.Critical)
End If
Next
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
CurrName = TextBox1.Text
' *** Error (apparently) happens here ***
For i = 0 To (UBound(Usernames))
If IfRepetition(Usernames, CurrName, i) = True Then
MsgBox("This username already exists!")
Else
ReDim Preserve Usernames(UBound(Usernames) + 1)
Usernames(UBound(Usernames)) = TextBox1.Text
ReDim Preserve Passwords(UBound(Passwords) + 1)
Passwords(UBound(Passwords)) = TextBox2.Text
End If
Next
End Sub
Private Function IfRepetition(ByRef Usernames() As String, CurrName As String, i As Integer) As Boolean
Dim j As Integer
'Checks for repetition of a username in the usernames array
IfRepetition = False
For j = 0 To (UBound(Usernames))
If Usernames(j) = CurrName Then
IfRepetition = True
Exit Function
End If
Next
End Function
End Class
The error you're getting is because UBound throws exception if the array is null.
Also using arrays for that isn't a good way, I recommend you use Dictionary for easier, shorter code.
Dim dic As New Dictionary(Of String, String) 'A new dictionary which handles usernames & passwords
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
'Login button
If String.IsNullOrWhiteSpace(TextBox1.Text) Then 'Check the entered username, if it's empty show error message and return ( don't continue )
MessageBox.Show("Enter the username")
Return
End If
If String.IsNullOrWhiteSpace(TextBox2.Text) Then 'Check the entered password, if it's empty show error message and return ( don't continue )
MessageBox.Show("Enter the password")
Return
End If
If Not dic.ContainsKey(TextBox1.Text) Then 'Check the entered username, if it doesn't exist show error message and return ( don't continue )
MessageBox.Show("The username is incorrect")
Return
End If
If dic(TextBox1.Text) <> TextBox2.Text Then 'Validate entered username and password, if it's wrong show error message and return ( don't continue )
MessageBox.Show("The password is incorrect")
Return
End If
Form3.Show() 'If none of above error messages appear which means the entered username and password are correct, show Form3 and hide this form
Me.Hide()
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
'create account button
If String.IsNullOrWhiteSpace(TextBox1.Text) Then 'Check the entered username, if it's empty show error message and return ( don't continue )
MessageBox.Show("Enter the username")
Return
End If
If String.IsNullOrWhiteSpace(TextBox2.Text) Then 'Check the entered password, if it's empty show error message and return ( don't continue )
MessageBox.Show("Enter the password")
Return
End If
If dic.ContainsKey(TextBox1.Text) Then 'Check the entered username, if it exists show error message and return ( don't continue )
MessageBox.Show("This username already exists")
Return
End If
dic.Add(TextBox1.Text, TextBox2.Text) 'If none of above error messages which means it's okay to create this account, Add the username & password to the dictionary
End Sub

Not fetching username and password from textfile

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim FILE_NAME As String = Cashierpath
System.IO.File.Exists(FILE_NAME) ' current
Dim objReader As StreamReader
Dim user As String = TextBox1.Text
Dim password As String = TextBox2.Text
Dim check As String
'Global Variable
'Dim DirPath7 As String = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "Scrap Data\Cashier Info\Cashiers\")
For Each filename As String In IO.Directory.EnumerateFiles(DirPath7, "*.txt")
Dim fName As String = IO.Path.GetFileName(filename)
If user = fName & ".txt" Then
objReader = New StreamReader(fName)
check = objReader.ReadToEnd()
If password = check Then
MessageBox.Show("Welcome " & user & "!")
Close()
My.Forms.Home.Show()
Else
MessageBox.Show("Username or Password is incorrect")
End If
End If
Next
End Sub
When the user enters their "username" and "password" into the textbox's, and clicks on this button, i want this button to check if there is a textfile with the name of the username entered, and if theres a file with that username it must then read it and check if the password matches the string inside the file. if it doesnt match it, it must then display a messagebox saying that "Username or password is incorrect", but nothing happens when i click on this button. No error message appears either.
Can someone take a look at my code and tell me what im doing wrong?
What you have there is an awful way to handle user credentials!
Read this for more information: Salted Password Hashing - Doing it Right
Regardless, you're way over-coding it.
Elsewhere in your app (correct use of Combine):
' Global Variable
Friend Shared DirPath7 As String = IO.Path.Combine(My.Computer.FileSystem.SpecialDirectories.MyDocuments, "Scrap Data", "Cashier Info", "Cashiers")
Button Handler:
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim User As String = TextBox1.Text.Trim
Dim Pass As String = TextBox2.Text.Trim
' Assemble the full expected file path, even if it might be malformed.
' The first case check protects against malformed path.
Dim FilePath As String = IO.Path.Combine(DirPath7, String.Format("{0}.txt", User))
Select Case True
Case User.Length = 0
MsgBox("Username is empty", vbExclamation, "Error")
Case Pass.Length = 0
MsgBox("Password is empty", vbExclamation, "Error")
Case Not IO.File.Exists(FilePath)
MsgBox("No file for User", vbExclamation, "Error")
Case Not IO.File.ReadAllText(FilePath) = Pass
MsgBox("Wrong Password", vbExclamation, "Error")
Case Else
MsgBox(String.Format("Welcome {0}!", User), vbOKOnly, "Success")
My.Forms.Home.Show()
End Select
End Sub
Dim objReader As StreamReader
Dim user As String = TextBox1.Text
Dim password As String = TextBox2.Text
Dim check As String
Dim fname = Path.Combine(DirPath7, String.Format("{0}.txt", user))
If File.Exists(fname) Then
Using objreader As New StreamReader(fname)
'objReader = StreamReader(fname)
check = objreader.ReadToEnd()
password = check
MessageBox.Show("Welcome " & user & "!")
Close()
My.Forms.Home.Show()
End Using
Else : MessageBox.Show("file not found, no user exists")
End If
removed the extra ".txt"
Added "Do Using" . . ."End Using"

Reading a text file into an array does nothing when Submit is clicked

I need this program to take the countries.txt file and read it into the country.countryarray when the program loads. Then the user needs to be able to enter a country name in the nmtext.text field and click submit and the country abbreviation should be pulled from the array and displayed in the abbrevtext.text field and complete the same action if the user searches an abbreviation from the abbrevtext.text field then it needs to display the country name in the nmtext.text field.
The countries.txt file has 250 countries and has to be stored in the debug file for the project and the contents of the file look like this when viewed in notepad++ with a carriage return at the end of each line.
0.AC
1.Ascension Island
2.AD
3.Andorra
4.AE
5.United Arab Emirates
6.AF
7.Afghanistan
8.AG
9.Antigua and Barbuda
10.AI
Here is my code so far and it is not working it will pop up the form and let me enter a country name but it doesn't do anything when I hit submit.
Imports System.IO
Imports Microsoft.VisualBasic.FileIO
Public Class CountForm
'CREATES STRUCTURE AND ARRAY
Public Structure Countries
Public CountryArray
Public CountryString As String
End Structure
'CREATES OBJECT FOR STRUCTURE
Public Country As Countries
'CREATES STREAM READER
Private MyStreamReader As System.IO.StreamReader
'CREATES FILESTRING VARIALE TO REFERENCE THE FILE PATH
Public FileString As String = "C:\Users\User\Desktop\Basic\CountryFile\CountryFile\bin\Debug\Countries.Txt"
'CREATES TEXTFIELDPARSER AND REFERENCES FILESTRING TO CALL THE FILEPATH
Private TextFieldParser As New TextFieldParser(FileString)
Private Sub CountForm_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Try
Country.CountryArray = File.ReadAllText(FileString) '// gets all the text in the file'
Catch ex As Exception
Dim ResponseDialogResult As String
' File missing.
ResponseDialogResult = MessageBox.Show("Something Went Wrong",
"Debuging Purposes", MessageBoxButtons.OK,
MessageBoxIcon.Question)
If ResponseDialogResult = DialogResult.Yes Then
End If
If ResponseDialogResult = DialogResult.No Then
' Exit the program.
Me.Close()
End If
End Try
End Sub
Private Sub Submit_Click(sender As System.Object, e As System.EventArgs) Handles Submit.Click
Try
TextFieldParser.TextFieldType = FieldType.Delimited
TextFieldParser.SetDelimiters(Environment.NewLine)
Do Until MyStreamReader.Peek = -1
If NmText.Text.ToUpper.Contains(Country.CountryArray.ToUpper()) Then
AbbrevText.Text = Country.CountryArray.ToUpper - 1
Else
MessageBox.Show("Name or Abbreviation Was Not Found", "Error", MessageBoxButtons.OK)
End If
Loop
Catch ex As Exception
End Try
End Sub
Private Sub Clear_Click(sender As System.Object, e As System.EventArgs) Handles Clear.Click
NmText.Text = ""
AbbrevText.Text = ""
End Sub
End Class
The StreamReader/TextFieldParser approach seems really complicated. Maybe this works for you:
Public Class Form1
Private countryDict As New Dictionary(Of String, String)
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Dim lineArray = IO.File.ReadAllLines("countries.txt")
'this will cause trouble if there is a NewLine at the end of the file
'In this case just remove the last new line.
For index = 0 To lineArray.Length - 2 Step 2
countryDict.Add(lineArray(index), lineArray(index + 1))
Next
End Sub
Private Sub Submit_Click(sender As System.Object, e As System.EventArgs) Handles Submit.Click
If countryDict.ContainsKey(NmText.Text.ToUpper()) Then
AbbrevText.Text = countryDict(NmText.Text.ToUpper())
Else
MsgBox("Name or Abbreviation Was Not Found")
End If
End Sub
End Class