Why do I keep on looping after I've filled in book info and why doesn't it write in to a file? - vb.net

Basically, it's an OOP task which creates a class called book. In the submain, there'll be a menu for the user to add new books/ view all book titles/ view all book authors and exit. I haven't got into the view all book titles and authors yet because at the moment I'm getting looped back again after I inserted the book's details. Which also prevents writing to a text file that will store previous books.
' Description: Making a menu that lets the user store their books info (like a librarian).
Sub Main()
'making a book using the attributes and methods
Dim title As String = ""
Dim datepublished As Date = #01/01/0001# ' date is in month/day/year
Dim pagenum As Integer = 0
Dim isbn As String = ""
Dim author As String = ""
Dim amountbooks As Integer = 0
Dim newbook As Book = New Book()
Dim choice As String = ""
'Writing and Reading a text file.
'CreateText creates a text file and returns system.io.streamwriter object.
Dim streamwriter As System.IO.StreamWriter
streamwriter = System.IO.File.CreateText("C:\Users\Local_PC\Desktop\Try_oop_book\bookrecords.txt")
'Making a menu for the client
' A While loop for the menu that checks the user's input
While choice <> "1" Or choice <> "2" Or choice <> "3" Or choice <> "4"
Console.Clear()
Console.WriteLine("----------LIBRARY MENU----------")
Console.WriteLine("[ 1 ]" & "Add New Book(s)")
Console.WriteLine("[ 2 ]" & "View all Book Titles")
Console.WriteLine("[ 3 ]" & "View all Authors")
Console.WriteLine("[ 4 ]" & "Exit")
choice = Console.ReadLine()
If choice <> "1" And choice <> "2" And choice <> "3" And choice <> "4" Then
Console.WriteLine("Please type in a valid input next time, press enter to retry again.")
Console.ReadLine()
Else
'Using choice, it goes to check which menu the user typed in.
If choice = "1" Then
'The user has chosen 1 which is to add new book(s) to the menu system.
'Setting the title of the book using mybook.setTitle
Console.WriteLine("How many books do you want to add?")
amountbooks = Console.ReadLine()
Dim bookarr(amountbooks) As Book 'This will initialise after amountbooks has been entered. Prevents from getting invalid index number of 0.
For x = 1 To amountbooks ' This loop will go over how many amount of books the user wants to add in to.
bookarr(x) = New Book()
Console.WriteLine("What is the title of the book?")
title = Console.ReadLine() 'This gives the value to store inside the variable 'title'
newbook.setTitle(title) 'This line will set that 'title' into array bookarr
Console.WriteLine("When is the book published?")
datepublished = Console.ReadLine()
newbook.setDatePublished(datepublished)
Console.WriteLine("How many page numbers are there?")
pagenum = Console.ReadLine()
newbook.setPageNum(pagenum)
Console.WriteLine("What is the ISBN(code) of the book?")
isbn = Console.ReadLine()
newbook.setISBN(isbn)
Console.WriteLine("Who is the author of the book?")
author = Console.ReadLine()
newbook.setAuthor(author)
Next x
End If
End If
End While
streamwriter.WriteLine(newbook)
End Sub

Change the while clause to replace 'Or' with 'AndAlso':
While choice <> "1" AndAlso choice <> "2" AndAlso choice <> "3" AndAlso choice <> "4"
In your current code if choice is 3 (for example) then it is not 1, 2 or 4 and the code will enter the while loop - in other words you have an infinite loop.

Related

Why is Visual Basics Console.ReadLine Buggy and can I fix it?

Hey question about a visual basics program, I am using Console.ReadLine into a string but it seems when I get to that part of the program or any part of my console program the keyboard enter key enters twice or something it completly skips a ReadLine and recieves the input.length 0 before I even have a chance to enter a string.
This isnt runable without my full code I dont think but I cant seem to get ReadLine to prompt for a string when it is initially run, it always returns 0 once and then loops normally. Im wondering if that has something to do with my keyboard or keyboard settings for a visual basics program or command line.
I dont think its a keyboard error because when I am entering code into visual basics it works fine and doesnt send two returns. I couldnt get the full code in code blocks.
...
Shared Sub Main()
Dim s As New Space()
Dim Ship As New Ships()
Dim Run As Boolean = True
Dim ChooseName As Boolean = True
Dim ch As Char
Dim PlayerName As String
While Run = True
s.PrintWelcome()
ch = Convert.ToChar(Console.Read())
If ch = "1" Then
While ChooseName = True
Console.WriteLine("Choose a Name Less then 50 Characters: ")
PlayerName = Console.ReadLine()
If PlayerName.Length > 50 Then
Console.WriteLine("Name is to Long!")
ElseIf PlayerName = "Q" Then
Run = False
Exit While
ElseIf PlayerName.Length <= 0 Then
Console.WriteLine("Please Enter a Player name or Q by itself to quit.")
Else
ChooseName = False
Console.WriteLine("PlayerName: " & PlayerName & " PlayerName.Length: {0}", PlayerName.Length)
End If
End While
If Run = True Then
End If
ElseIf ch = "2" Then
ElseIf ch = "3" Then
Run = False
ElseIf ch = "Q" Then
Run = False
Else
s.PrintWelcome()
End If
End While
End Sub
...
I suspect that you really ought to be structuring your code more like this:
Module Module1
Sub Main()
Do
Console.Write("Please select a menu item from 1, 2, 3 or Q to quit: ")
Dim menuSelection = Console.ReadKey()
Dim input As String = Nothing
Console.WriteLine()
Select Case menuSelection.KeyChar
Case "1"c
Console.WriteLine("What did you want to say about 1?")
input = Console.ReadLine()
Case "2"c
Console.WriteLine("What did you want to say about 2?")
input = Console.ReadLine()
Case "3"c
Console.WriteLine("What did you want to say about 3?")
input = Console.ReadLine()
Case "q"c, "Q"c
Exit Do
Case Else
'Do nothing before repeating the prompt.
End Select
If Not String.IsNullOrEmpty(input) Then
Console.WriteLine("You said: " & input)
End If
Loop
End Sub
End Module
The ReadKey call will immediately read the first key entered by the user. Rather than requiring the user to hit Enter after that key, the application writes the line break itself. It then tests the chararacter represented by that key to see if it is a valid menu item. If it is, it does whatever is appropriate for that item, whether that be reading a line of input or quitting. If the key does not represent a valid menu item then it simply loops back to the prompt. Note also that the Char value entered by the user is actually compared to Char literals, the way it should be done, rather than String literals.

Vb.net Data is not being incremented and added to list

I'm having an issue trying to create a program that takes user input for a text file's location containing medical records. The diseases and number of patients are being added to a list. I'm having an issue where my console is printing 0 for both the total of XX unique diseases and YYY patient encounters. I am not getting any errors, just not the correct output.
I believe my issue is in my processData() sub, however I am unsure why it's printing back 0. Also, how do I go about keeping track of duplicate diseases that are added to the list as I'm trying to add a counter next to each time the disease is seen.
Sample from Disease.txt
3710079 JUDITH CLOUTIER 2012-08-04 Spastic Colonitis
3680080 VIRGINIA ALMOND 2012-07-25 Chronic Phlegm
3660068 ELLEN ENGLEHARDT 2012-04-06 Whooping Cough
3810076 LILLIAN KEMMER 2014-07-04 Scurvy
3630055 TERESA BANASZAK 2012-06-15 Scurvy
Output:
There were a total of 0 unique diseases observed.
A total of 0 patient encounters were held
Main():
' Global variables
Dim inputFile As String
Dim patientCounter = 0
Dim diseaseList As New List(Of String)
Dim dateList As New List(Of Date)
Sub Main()
Dim reportFile As String
Dim yn As String
Console.ForegroundColor = ConsoleColor.Yellow
Console.BackgroundColor = ConsoleColor.Blue
Console.Title = "Medical Practice Data Analysis Application"
Console.Clear()
Console.WriteLine("Please enter the path and name of the file to process:")
inputFile = Console.ReadLine
If (File.Exists(inputFile)) Then
' Call to processData sub if input file exists
processData()
Console.WriteLine(vbCrLf & "Processing Completed...")
Console.WriteLine(vbCrLf & "Please enter the path and name of the report file to generate")
reportFile = Console.ReadLine
File.Create(reportFile).Dispose()
If (File.Exists(reportFile)) Then
Console.WriteLine(vbCrLf & "Report File Generation Completed...")
Else
' Call to sub to end program if directory does not exist
closeProgram()
End If
' Get user input to see report
Console.WriteLine(vbCrLf & "Would you like to see the report file [Y/n]")
yn = Console.ReadLine
' If user inputs "y" or "Y" then print report
' Otherwise close the program
If (yn = "y" OrElse "Y") Then
printFile()
Else
closeProgram()
End If
Else
' Call to sub to end program if file does not exist
closeProgram()
End If
Console.ReadLine()
End Sub
processData Sub():
Public Sub processData()
Dim lines As String() = File.ReadAllLines(inputFile)
Dim tab
Dim dates
Dim diseaseCounter = 0
For Each line As String In lines
tab = line.Split(vbTab)
patientCounter += 1
dates = Date.Parse(line(3))
dateList.Add(dates)
'diseaseList.Add(line(4))
Dim disease As New disease(line(4))
diseaseList.Add(disease.ToString)
'diseaseList(line(4)).
For Each value In diseaseList
'If value.Equals(line(4)) Then disease.counter += 1
Next
Next
Dim uniqueDiseases As String() = diseaseList.Distinct().ToArray
End Sub
Disease.class
Class disease
Dim counter As Integer = 0
Dim name As String = ""
Sub New(newDisease As String)
name = newDisease
counter = 0
End Sub
End Class
printFile()
Sub printFile()
Dim muchoMedical As String = "MuchoMedical Health Center"
Dim diseaseReport As String = "Disease Report For the Period " & "earliest_date" & " through " & "latest_date"
Console.WriteLine(vbCrLf & muchoMedical.PadLeft(Console.WindowWidth / 2))
Console.WriteLine(diseaseReport.PadLeft(Console.WindowWidth / 2))
Console.WriteLine(vbCrLf & "There were a total of " & diseaseList.Count & " unique diseases observed")
Console.WriteLine("A total of " & patientCounter & " patient encounters were held")
Console.WriteLine(vbCrLf & "Relative Histogram of each disease")
For Each disease As String In diseaseList
Console.WriteLine(vbCrLf & disease & vbTab & " ")
Next
End Sub
closeProgram()
Sub closeProgram()
Console.WriteLine(vbCrLf & "File does not exist")
Console.WriteLine("Press Enter to exit the program...")
Console.ReadLine()
End Sub
You don't need a disease class, really, if the most complicated thing you are doing is counting disease occurrences (your disease class had no public members so I don't know what you were doing there anyway). You can simply do everything with a little LINQ.
' processing section
Dim lines = File.ReadAllLines(inputFile)
Dim splitLines = lines.Select(Function(l) l.Split({vbTab}, StringSplitOptions.RemoveEmptyEntries))
Dim diseaseGrouping = splitLines.GroupBy(Function(s) s(3))
Dim patients = splitLines.Select(Function(s) s(1))
Dim dates = splitLines.Select(Function(s) DateTime.Parse(s(2)))
' report section
Dim padAmount = CInt(Console.WindowWidth / 2)
Dim muchoMedical As String = "MuchoMedical Health Center"
Dim diseaseReport As String = $"Disease Report For the Period {dates.Min():d} through {dates.Max():d}"
Console.WriteLine()
Console.WriteLine(muchoMedical.PadLeft(padAmount))
Console.WriteLine(diseaseReport.PadLeft(padAmount))
Console.WriteLine()
Console.WriteLine($"There were a total of {diseaseGrouping.Count()} unique diseases observed.")
Console.WriteLine($"A total of {patients.Count()} patient encounters were held")
For Each diseaseAndCount In diseaseGrouping
Console.WriteLine()
Console.WriteLine($"{diseaseAndCount.Key}{vbTab}{diseaseAndCount.Count()}")
Next
I think your disease name is in index 3. You were looking at 4 originally. Maybe you have a tab between first and last name? Change it if I was wrong. This may apply to any or all of the indices.
Output:
MuchoMedical Health Center
Disease Report For the Period 4/6/2012 through 7/4/2014
There were a total of 4 unique diseases observed.
A total of 5 patient encounters were held
Spastic Colonitis 1
Chronic Phlegm 1
Whooping Cough 1
Scurvy 2
I think the main issue with your code as listed above is that in the processData sub you have:
For Each line As String In lines
tab = line.Split(vbTab)
patientCounter += 1
dates = Date.Parse(line(3))
dateList.Add(dates)
'diseaseList.Add(line(4))
Dim disease As New disease(line(4))
diseaseList.Add(disease.ToString)
'diseaseList(line(4)).
For Each value In diseaseList
'If value.Equals(line(4)) Then disease.counter += 1
Next
Next
I think you more likely mean to use tab(3) and tab(4) instead of line(3) and line(4) etc. You split the line into the "tab" variable but then don't use it. While you could rewrite everything and handle it differently, if you want to go with what you've got, I think that's your core error.
I liked your idea of a class. You can wrap up all your data in one list. I enhanced your class so it could contain all the data in the file. Public Properties are automatic properties that have Get, Set, and the Private fields that hold the data written by the compiler. I have added an Overrides of the .ToString because you were not getting the results you expected. We have the parameterized constructor like you have except expanded to include all the properties.
The magic comes in the Linq query. The d stands for an item in the diseaseList which is an instance of the Disease class. Then I added an order by clause which will produce the results in alphabetical order by DiseaseName which is a string. Grouping by the unique DiseaseName into a Group with Count.
Notice in the second For Each loop we have all the properties of the class available.
I happened to be in a Windows Forms app so I used Debug.Print. Just replace with Console.WriteLine. I leave to you the fancy formatting if you desire.
Public Class Disease
Public Property Name As String
Public Property DiagnosisDate As Date
Public Property DiseaseName As String
Public Property ID As Integer
Public Sub New(PatientID As Integer, PatientName As String, dDate As Date, sDisease As String)
ID = PatientID
Name = PatientName
DiagnosisDate = dDate
DiseaseName = sDisease
End Sub
'If you don't override ToString you will get the fully qualified name of the class
'You can return any combination of the Properties as long as the end
'result is a string
Public Overrides Function ToString() As String
Return Name
End Function
End Class
Public Sub processData()
Dim lines As String() = File.ReadAllLines(inputFile)
Dim diseaseList As New List(Of Disease)
For Each line As String In lines
'I was having trouble with the tabs so I changed it to a comma in the file
'3710079,JUDITH CLOUTIER,2012-08-04,Spastic Colonitis
'the small c following the "," tells the compiler that this is a Char
Dim tab = line.Split(","c)
Dim inputDate = Date.ParseExact(tab(2), "yyyy-MM-dd", CultureInfo.InvariantCulture)
Dim Studentdisease As New Disease(CInt(tab(0)), tab(1), inputDate, tab(3))
diseaseList.Add(Studentdisease)
Next
Dim diseaseGrouping = From d In diseaseList
Order By d.DiseaseName
Group By d.DiseaseName
Into Group, Count
For Each diseaseAndCount In diseaseGrouping
Debug.Print($"{diseaseAndCount.DiseaseName} {diseaseAndCount.Count()} ")
For Each d In diseaseAndCount.Group
Debug.Print($" {d.Name}, {d.DiagnosisDate.ToShortDateString}")
Next
Next
End Sub

Storing string then displaying it with a label box

I am trying to store the string from an input box and then display it with dashes in the lblbox for a hangman game for a class.
These are the tasks that I am struggling with:
edit the program to allow a Secret Word of any length.
the program will allow the ‘guesser’ to guess 2 times the length of the word. As an example, the word ‘code’ will allow 8 total guesses.
As the user guesses at letters contained in the word the program will:
Count the number of attempts the user has completed.
Replace the appropriate dash (-) with the correct letter, if the correct letter has been guessed.
When all the letters have been guessed correctly all the dashes (-) should be replaced with the appropriate letters, and a message box should appear stating “Great Job playing Hangman.!”
If the user is unable to guess the correct word in the amount of guesses allowed; the dashes (-) should be replaced with GAME OVER! and a message box should appear stating “Sorry the correct word was________”
2 bonus points will be awarded for displaying all incorrect letters guess in a 3rd label control.
4 more additional bonus points will be awarded for not allowing, or counting a user who guesses the same incorrect letter twice.
Here is my code:
Dim strSecretWord As String
Dim strLetterGuessed As String
Dim blnDashReplaced As Boolean
Dim intNumberOfRemainingGuesses As Integer = 10
Dim intNumofGuesses As Integer = 0
lblSecretWord.Text = ""
lblNumberOfAttempts.Text = ""
'start game and have 1st user input a 5 letter word that 2nd player needs to guess
strSecretWord = InputBox("Please input a 5 letter word for user to guess:", "Please input secret word.").ToUpper
'displays five dashes for the secret word
lblSecretWord.Text = lblSecretWord.Text & "-----"
'guessing player recieves inputbox to make letter guesses
MessageBox.Show("The length of the word is 5 letters, you will be given 10 guesses", "10 guesses", MessageBoxButtons.OK)
MessageBox.Show("Player who gets to guess, BE READY!", "Good Luck Guessing", MessageBoxButtons.OK)
'Counts number of attempts player gets (10) and replaces dashes with guessed letter if correct
'If guessed letter was incorrect, user loses a turn
For intNumberofGuesses = 1 To 10
strLetterGuessed = InputBox("Please guess a letter:", "Letter Guess").ToUpper
'Uses an IntIndex counter of 0 to 4 to execute 5 times (5 dashes)
'Also uses the value of intIndex to check each of the 5 locations of the strSecretWord
For intIndex As Integer = 0 To 4
'if the user has guessed a correct letter then remove a dash and insert the correct letter guessed
If strSecretWord.Substring(intIndex, 1) = strLetterGuessed Then
lblSecretWord.Text = lblSecretWord.Text.Remove(intIndex, 1)
lblSecretWord.Text = lblSecretWord.Text.Insert(intIndex, strLetterGuessed)
blnDashReplaced = True
End If
Next intIndex
'If the user guessed a correct letter on their last guess the blnDashReplaced is set and the true condition of the If statement is executed
If blnDashReplaced = True Then
'if there are no more dashes, and the game has been solved.
If lblSecretWord.Text.Contains("-") = False Then
MessageBox.Show("Great Job playign Hangman!", "Game Over", MessageBoxButtons.OK)
lblRemainingNumberOfAttempts.Text = ""
lblNumberOfAttempts.Text = ""
Exit Sub
Else
blnDashReplaced = False
End If
Else
End If
lblNumberOfAttempts.Text = intNumberofGuesses
intNumberOfRemainingGuesses = intNumberOfRemainingGuesses - 1
lblRemainingNumberOfAttempts.Text = intNumberOfRemainingGuesses
Next
lblSecretWord.Text = "GAME OVER!"
MessageBox.Show("Better luck next time. Sorry the correct word was " & strSecretWord & ".", "You Lost", MessageBoxButtons.OK)
lblRemainingNumberOfAttempts.Text = ""
lblNumberOfAttempts.Text = ""
I added a list box to keep the guessed letters. Other comments and explanations in line.
Public Class Form3
'Move this to a class level variable so it can be seen by
'all the methods in the class
Private strSecretWord As String
Private Sub btnStartGame_Click(sender As Object, e As EventArgs) Handles btnStartGame.Click
Dim strLetterGuessed As String
Dim blnDashReplaced As Boolean
Dim intNumberOfRemainingGuesses As Integer
Dim intNumofGuesses As Integer = 0
'Display correct number of dashes
Dim numberOfDashes As Integer = strSecretWord.Length
'Create a string with correct number of dashes
'This uses and overload of the String constructor that takes a Char and an integer
'as arguments and returns a string with that character repeated that number
'of times. The lower case c following "-" indicates that - is a Char.
Dim TotalNumofGuesses = numberOfDashes * 2
lblRemainingNumberOfAttempts.Text = TotalNumofGuesses.ToString
intNumberOfRemainingGuesses = TotalNumofGuesses
Dim dashString As String = New String("-"c, numberOfDashes)
'displays the dashes
lblSecretWord.Text = dashString
'guessing player recieves inputbox to make letter guesses
'You can use an Interpolated string to display variables in line surrounded by { }.
'In older versions of VB String.Format() will yield the same result.
MessageBox.Show($"The length of the word is {numberOfDashes} letters, you will be given {TotalNumofGuesses} guesses", $"{TotalNumofGuesses} guesses", MessageBoxButtons.OK)
MessageBox.Show("Player who gets to guess, BE READY!", "Good Luck Guessing", MessageBoxButtons.OK)
'Counts number of attempts player gets and replaces dashes with guessed letter if correct
'If guessed letter was incorrect, user loses a turn
For counter = 1 To TotalNumofGuesses
strLetterGuessed = InputBox("Please guess a letter:", "Letter Guess").ToUpper
'If lstLettersGuessed.Contains(strLetterGuessed) Then
If lbxLettersGuessed.Items.Contains(strLetterGuessed) Then
MessageBox.Show($"{strLetterGuessed} has already been guessed.", "Try Again")
'need to do this so they are not cheated out of a guess
TotalNumofGuesses += 1
Continue For 'Moves to the next iteration of the For
End If
lbxLettersGuessed.Items.Add(strLetterGuessed)
'lstLettersGuessed.Add(strLetterGuessed)
'Uses an IntIndex counter of 0 to 4 to execute 5 times (5 dashes)
'Also uses the value of intIndex to check each of the 5 locations of the strSecretWord
For intIndex As Integer = 0 To numberOfDashes - 1
'if the user has guessed a correct letter then remove a dash and insert the correct letter guessed
If strSecretWord.Substring(intIndex, 1) = strLetterGuessed Then
lblSecretWord.Text = lblSecretWord.Text.Remove(intIndex, 1)
lblSecretWord.Text = lblSecretWord.Text.Insert(intIndex, strLetterGuessed)
blnDashReplaced = True
End If
Next intIndex
'If the user guessed a correct letter on their last guess the blnDashReplaced is set and the true condition of the If statement is executed
If blnDashReplaced = True Then
'if there are no more dashes, and the game has been solved.
If lblSecretWord.Text.Contains("-") = False Then
MessageBox.Show("Great Job playing Hangman!", "Game Over", MessageBoxButtons.OK)
'Do this at start of game, player wants to see final score
'lblRemainingNumberOfAttempts.Text = ""
'lblNumberOfAttempts.Text = ""
Exit Sub
Else
blnDashReplaced = False
End If
End If
'This is a shorter way of incrementing a variable
intNumofGuesses += 1
'Can't put an integer into a Text property, it needs a string
lblNumberOfAttempts.Text = intNumofGuesses.ToString
'This is a shorter way of decrementing a variable
intNumberOfRemainingGuesses -= 1
'Can't put an integer into a Text property, it needs a string
lblRemainingNumberOfAttempts.Text = intNumberOfRemainingGuesses.ToString
Next
lblSecretWord.Text = "GAME OVER!"
MessageBox.Show("Better luck next time. Sorry the correct word was " & strSecretWord & ".", "You Lost", MessageBoxButtons.OK)
'Do this at start of game
'lblRemainingNumberOfAttempts.Text = ""
'lblNumberOfAttempts.Text = ""
End Sub
Private Sub btnSetUp_Click(sender As Object, e As EventArgs) Handles btnSetUp.Click
lblSecretWord.Text = ""
lblNumberOfAttempts.Text = "0"
lblRemainingNumberOfAttempts.Text = "0"
lbxLettersGuessed.Items.Clear()
'start game and have 1st user input a 5 letter word that 2nd player needs to guess
strSecretWord = InputBox("Please input a word for user to guess:", "Please input secret word.").ToUpper
End Sub
End Class

VB 2008 Transferring stored values to textbox after initial textbox value is cleared

Self teaching VB beginner here.
I have a data entry section that includes...
2 comboboxes(cbx_TruckType, cbx_DoorNumber)
-------cbx_TruckType having 2 options (Inbound, Outbound)
-------cbx_DoorNumber having 3 options (Door 1, Door 2, Door 3)
2 textboxes (txb_CustomerName, txb_OrderNumber)
-------txb_CustomerName will hold a customer name
-------txb_OrderNumber will hold an order number
and finally...
a button(btn_EnterTruck) that transfers the text from the comboxes and textboxes to the following...
2 Tabs
The 1st tab has
2 buttons(btn_Door1, btn_Door2)
btn_Door1 has 3 corresponding textboxes
-------txb_TruckTypeDoor1, txb_CustomerNameDoor1, txb_OrderNumberDoor1
btn_Door2 has 3 corresponding textboxes
-------txb_TruckTypeDoor2, txb_CustomerNameDoor2, txb_OrderNumberDoor2
The 2nd tab has
1 button(btn_Door3)
btn_Door1 has 3 corresponding textboxes
-------txb_TruckTypeDoor3, txb_CustomerNameDoor3, txb_OrderNumberDoor3
Currently, I have code (that works thanks to another question I had!) that, upon btn_EnterTruck.click, will transfer the text to the corresponding textboxes.
Here's my problem...
I've coded a msgbox to pop-up (when Inbound is selected from the cbx_TruckType) asking if there is an Outbound. If I click "Yes", an inputbox pops-up and asks for an order number. The button then transfers the Inbound information to the textboxes and stores the Outbound order number.
When I click btn_Door1(or 2 or 3), it clears the text from its corresponding textboxes. (Using me.controls)
( I would add code for all of the above, but I figure its a moot point, because it works)
What I want to happen...
I want to have the stored Outbound number to be saved with a reference to which door number it corresponds to. Then upon btn_DoorX click, it will fill that order number into the corresponding textbox. I don't need the text stored/saved when the app is closed.
And I have no idea how to do that.
*After some tooling, I've done the following, but it does not work"
I declared these at the class level.
Dim str_SameTruckPODoor1, str_SameTruckPODoor2, str_SameTruckPODoor3 As String
This code is in the btn_EnterTruck event
Dim str_ErrOutDoorName As String = cbx_DoorNumber.Text
Dim str_OutboundDoorName As String = str_ErrOutDoorName.Replace(" ", "")
Dim ArrayForPONumbers As Control() = Me.Controls.Find("str_SameTruckPO" & str_OutboundDoorName, True)
If cbx_TruckType.Text = "Inbound" Then
Dim OutboundMsg = "Is there an Outbound with this truck information?"
Dim Title = "Outbound?"
Dim style = MsgBoxStyle.YesNo Or MsgBoxStyle.DefaultButton2 Or _
MsgBoxStyle.Question
Dim response = MsgBox(OutboundMsg, style, Title)
If response = MsgBoxResult.Yes Then
Dim NeedPOMessage, NeedPOTitle, defaultValue As String
Dim PONumberOutbound As String
' Set prompt.
NeedPOMessage = "Enter the PO Number"
' Set title.
NeedPOTitle = "PO# For Outbound"
defaultValue = "?" ' Set default value.
' Display message, title, and default value.
PONumberOutbound = InputBox(NeedPOMessage, NeedPOTitle, defaultValue)
' If user has clicked Cancel, set myValue to defaultValue
If PONumberOutbound Is "" Then PONumberOutbound = defaultValue
ArrayForPONumbers(0) = PONumberOutbound
End If
End If
I'm getting an error message on
ArrayForPONumbers(0) = PONumberOutbound ' Cannot convert string to .controls
And I have the following code in the btn_Door1 event - it handles btn_Door2, btn_Door3
Dim WhichButton As Button = CType(sender, Button)
Dim str_ErrDoorName As String = WhichButton.Name
Dim str_DoorName As String = str_ErrDoorName.Replace("btn_", "")
Dim str_DoorType As Control() = Me.Controls.Find("txb_" & str_DoorName & "Type", True)
Dim str_Customer As Control() = Me.Controls.Find("txb_" & str_DoorName & "Customer", True)
Dim str_OrderNumber As Control() = Me.Controls.Find("txb_" & str_DoorName & "OrderNumber", True)
Dim SecondArrayForPONumbers As Control() = Me.Controls.Find("str_SameTruckPO" & str_DoorName, True)
If str_DoorType(0).Text = "Outbound" Then
str_DoorType(0).Text = ""
str_Customer(0).Text = ""
str_OrderNumber(0).Text = ""
ElseIf SecondArrayForPONumbers(0).Text.Length > 0 Then
str_DoorType(0).Text = "Outbound"
str_OrderNumber(0).Text = Me.Controls("str_SameTruckPO" & str_DoorName).Text
End If
Any help is appreciated. If I'm not clear on what I'm asking or haven't given enough details, please let me know.
Edit: Added info based on comment, Added code, Changed Title
How long do you want this data to be stored? IE: longer than the life of the open application? If the application is closed is it alright if the data is lost? If not, you may want to consider writing this data to an external database.

Search string to add line after specific word in VB.net

(I am a VERY basic programmer)
I have a body of text which needs searching through to find a specific word "Customer" and then save the next line as the CustomerName (CustomerName = >line of text<)
If your "body of text" is a TextBox you could take profit of the .Lines property:
Dim index As Integer
Dim customerName As String = ""
For i As Integer = 1 to TextBox1.Lines.Length - 1
If TextBox1.Lines(i-1).Contains("Customer") Then
customerName = TextBox1.Lines(i)
Exit For
End If
Next
If you have a plain text, you can obtain the lines splitting the whole text:
Dim lines() As String = sAllText.Split(Environment.NewLine())
And then doing the same as before, but instead of using TextBox1.Lines, use lines.