how to make inputBox's ok and [Enter] key press make it pop up again with a loop - vb.net

The main question is: how can i make InputBox keep poping up when the user either clicks Ok or presses [Enter] on the keyboard? This program stores each value in a sequential access file.
Option Explicit On
Option Strict On
Option Infer Off
Public Class frmMain
Private Sub btnExit_Click(sender As Object, e As EventArgs) Handles btnExit.Click
End Sub
Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
Dim outFile As IO.StreamWriter
Dim strInput As String
Dim dblInput As Double
'Do
strInput = InputBox("Enter A Number", "Test Scores Project")
Double.TryParse(strInput, dblInput)
outFile = IO.File.CreateText("Scores.txt")
outFile.WriteLine(dblInput)
'While user presses the enter button or ok keep asking for more numbers
outFile.Close()
Me.Close()
End Sub
Private Sub btnCount_Click(sender As Object, e As EventArgs) Handles btnCount.Click
Dim inFile As IO.StreamReader
Dim strMessage As String
Dim intFiles As Integer
If IO.File.Exists("Scores.txt") Then
inFile = IO.File.OpenText("Scores.txt")
Else
MessageBox.Show("No such file exists", "Text Scores Project")
End If
Do Until inFile.Peek = -1
strMessage = inFile.ReadLine
intFiles += 1
Loop
lblNumber.Text = intFiles.ToString
End Sub
End Class

Try initializing outfile in the declaration:
Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
Using outFile As New IO.StreamWriter("Scores.txt")
Dim strInput As String
Dim dblInput As Double
Do
strInput = InputBox("Enter A Number(done when finished)", "Test Scores Project")
If Double.TryParse(strInput, dblInput) Then
outFile.WriteLine(dblInput)
End If
While strInput <> "done"
End Using
Me.Close()
End Sub
A simple while loop will work here.
Note: The use of the Using block. This handles all the clean up of the stream.

The reason you're getting that warning about inFile is because the compiler recognizes that the code path could go through the Else branch of If IO.File.Exists("Scores.txt") without ever assigning a value to inFile.
Try doing this: Dim inFile As IO.StreamReader = Nothing

Related

How to Save Textboxt.Text as file name?

What's wrong with this code?
I need to add textbox13.text (the value of it is in number) as the file name and how can I add an option which checks if the file already exists if so show an option saying replace or cancel when I press my save button.
So far here is the code :
Dim i As Integer = 0
Dim filepath As String = IO.Path.Combine("D:\Logs", Textbox13.Text + i.ToString() + ".txt")
Using sw As New StreamWriter(filepath)
sw.WriteLine(TextBox13.Text)
sw.WriteLine(TextBox1.Text)
sw.WriteLine(TextBox2.Text)
sw.WriteLine(TextBox3.Text)
sw.WriteLine(TextBox4.Text)
sw.WriteLine(TextBox5.Text)
sw.WriteLine(TextBox7.Text)
sw.WriteLine(TextBox9.Text)
sw.WriteLine(TextBox10.Text)
sw.WriteLine(TextBox11.Text)
sw.WriteLine(TextBox12.Text)
This is from Form1
Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
Form2.WriteTextBoxTextToLabel(TextBox1.Text)
Form2.WriteTextBoxTextToTextbox(TextBox1.Text)
End Sub
This is from form2
Public Sub WriteTextBoxTextToLabel(ByVal Txt As String)
lblPD.Text = Txt
End Sub
Public Sub WriteTextBoxTextToTextbox(ByVal Txt As String)
TextBox13.Text = Txt
End Sub
Private Sub TextBox13_TextChanged(sender As Object, e As EventArgs) Handles TextBox13.TextChanged
TextBox13.Text = lblPD.Text
End Sub
You can add the following logic before creating the StreamWriter:
if system.io.file.exists(filepath) then
' The file exists
else
' The file does not exist
end if

ProgressBar not updating using a For Each loop

I'm copying all the .avi and .png files from one folder into another:
Private Sub CopierSend_Button_Click(sender As Object, e As EventArgs) Handles CopierSend_Button.Click
If MessageBox.Show("Click OK to send media or just Cancel.", "Media Copier", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) = DialogResult.OK Then
For Each foundFile As String In My.Computer.FileSystem.GetFiles(FrapsFolder_, Microsoft.VisualBasic.FileIO.SearchOption.SearchTopLevelOnly, "*.avi", "*.png")
Dim foundFileInfo As New System.IO.FileInfo(foundFile)
My.Computer.FileSystem.CopyFile(foundFile, DestFolder_ & foundFileInfo.Name, Microsoft.VisualBasic.FileIO.UIOption.OnlyErrorDialogs, Microsoft.VisualBasic.FileIO.UICancelOption.DoNothing)
Next
Else
'Nothing Yet
End If
End Sub
I want to add a ProgressBar which will count every time a file is copied, so I added this code before the For Each loop:
Dim file1() As String = IO.Directory.GetFiles(FrapsFolder_, "*.avi")
Dim file2() As String = IO.Directory.GetFiles(FrapsFolder_, "*.png")
Dim files = file1.Length + file2.Length
Copier_ProgressBar.Step = 1
Copier_ProgressBar.Maximum = files
And added this code inside the For Each loop:
Copier_ProgressBar.Value += 1
Here is all of my code:
Private Sub CopierSend_Button_Click(sender As Object, e As EventArgs) Handles CopierSend_Button.Click
If MessageBox.Show("Click OK to send media or just Cancel.", "Media Copier", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) = DialogResult.OK Then
Dim file1() As String = IO.Directory.GetFiles(FrapsFolder_, "*.avi")
Dim file2() As String = IO.Directory.GetFiles(FrapsFolder_, "*.png")
Dim files = file1.Length + file2.Length
Copier_ProgressBar.Step = 1
Copier_ProgressBar.Maximum = files
For Each foundFile As String In My.Computer.FileSystem.GetFiles(FrapsFolder_, Microsoft.VisualBasic.FileIO.SearchOption.SearchTopLevelOnly, "*.avi", "*.png")
Dim foundFileInfo As New System.IO.FileInfo(foundFile)
My.Computer.FileSystem.CopyFile(foundFile, DestFolder_ & foundFileInfo.Name, Microsoft.VisualBasic.FileIO.UIOption.OnlyErrorDialogs, Microsoft.VisualBasic.FileIO.UICancelOption.DoNothing)
Copier_ProgressBar.Value += 1
Next
Else
'Nothing Yet
End If
End Sub
The ProgressBar updates, but only after all the files have been copied instead of updating in real time. Any idea?
As it stands it looks like the ProgressBar doesn't do anything until after all the files have copied. That isn't strictly true. Instead your UI is not updating.
Instead you should look into using a BackgroundWoker to report progress. Something like this should do the trick:
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'This can also be set using the Designer
BackgroundWorker1.WorkerReportsProgress = True
End Sub
Private Sub CopierSend_Button_Click(sender As Object, e As EventArgs) Handles CopierSend_Button.Click
If MessageBox.Show("Click OK to send media or just Cancel.", "Media Copier", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) = DialogResult.OK Then
Dim file1() As String = IO.Directory.GetFiles(FrapsFolder_, "*.avi")
Dim file2() As String = IO.Directory.GetFiles(FrapsFolder_, "*.png")
Dim files As Integer = file1.Length + file2.Length
Copier_ProgressBar.Step = 1
Copier_ProgressBar.Maximum = files
BackgroundWorker1.RunWorkerAsync()
End If
End Sub
Private Sub BackgroundWorker1_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
For Each foundFile As String In My.Computer.FileSystem.GetFiles(FrapsFolder_, Microsoft.VisualBasic.FileIO.SearchOption.SearchTopLevelOnly, "*.avi", "*.png")
Dim foundFileInfo As New System.IO.FileInfo(foundFile)
My.Computer.FileSystem.CopyFile(foundFile, DestFolder_ & foundFileInfo.Name, Microsoft.VisualBasic.FileIO.UIOption.OnlyErrorDialogs, Microsoft.VisualBasic.FileIO.UICancelOption.DoNothing)
BackgroundWorker1.ReportProgress(Copier_ProgressBar.Value + 1)
Next
End Sub
Private Sub BackgroundWorker1_ProgressChanged(sender As Object, e As System.ComponentModel.ProgressChangedEventArgs) Handles BackgroundWorker1.ProgressChanged
Copier_ProgressBar.Value = e.ProgressPercentage
End Sub
As an additional note, for best practice, I would consider using Path.Combine instead of concatenating strings together:
My.Computer.FileSystem.CopyFile(foundFile, Path.Combine(DestFolder_, foundFileInfo.Name), Microsoft.VisualBasic.FileIO.UIOption.OnlyErrorDialogs, Microsoft.VisualBasic.FileIO.UICancelOption.DoNothing)

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

Variables are used before it is assigned a null value. Using StreamReader

I decided to try one of the advanced exercises in my book, it needs me to edit a program. Before getting the artist name and price, the btn.Add_Click procedure should determine whether the CD name is already included in the list box. If the list box contains the CD name, the procedure should display an appropriate message and then not add the CD to the list. Problem is the Do Until inFile.Peek = -1 and the For Each Name As String In strNameCollection apparently are assigned a null value. Any ideas on why this is or possibly how to get this to work? btn.Add_Click is towards the bottom of the code
Option Explicit On
Option Strict On
Option Infer Off
Public Class frmMain
Private Sub btnExit_Click(sender As Object, e As EventArgs) Handles btnExit.Click
Me.Close()
End Sub
Private Sub frmMain_FormClosing(sender As Object, e As Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
' save the list box information
' declare a StreamWriter variable
Dim outFile As IO.StreamWriter
' open the file for output
outFile = IO.File.CreateText("CDs.txt")
' write each line in the list box
For intIndex As Integer = 0 To lstCds.Items.Count - 1
outFile.WriteLine(lstCds.Items(intIndex))
Next intIndex
' close the file
outFile.Close()
End Sub
Private Sub frmMain_Load(sender As Object, e As EventArgs) Handles Me.Load
' fills the list box with data
' stored in a sequential access file
' declare variables
Dim inFile As IO.StreamReader
Dim strInfo As String
' verify that the file exists
If IO.File.Exists("CDs.txt") Then
' open the file for input
inFile = IO.File.OpenText("CDs.txt")
' process loop instructions until end of file
Do Until inFile.Peek = -1
strInfo = inFile.ReadLine
lstCds.Items.Add(strInfo)
Loop
inFile.Close()
' select the first line in the list box
lstCds.SelectedIndex = 0
Else
MessageBox.Show("Can't find the CDs.txt file",
"CD Collection",
MessageBoxButtons.OK,
MessageBoxIcon.Information)
End If
End Sub
Private Sub btnAdd_Click(sender As Object, e As EventArgs) Handles btnAdd.Click
' adds CD information to the list box
' declare variables
Dim strName As String
Dim strArtist As String
Dim strPrice As String
Dim strConcatenatedInfo As String
Dim dblPrice As Double
Dim strNameCollection() As String
'read all names into array
Dim inFile As IO.StreamReader
If IO.File.Exists("CDs.txt") Then
' open the file for input
inFile = IO.File.OpenText("CDs.txt")
End If
'read all names into array
Dim index As Integer = 0
Do Until inFile.Peek = -1
ReDim strNameCollection(index)
strNameCollection(index) = inFile.ReadLine
Loop
inFile.Close()
' get the CD information
strName = InputBox("CD name:", "CD Collection")
For Each Name As String In strNameCollection
If strName = Name Then
MessageBox.Show("Sorry that name was alread on the list", "CD Project",
MessageBoxButtons.OK, MessageBoxIcon.Asterisk)
Else
strArtist = InputBox("Artist:", "CD Collection")
strPrice = InputBox("Price:", "CD Collection")
Double.TryParse(strPrice, dblPrice)
strPrice = dblPrice.ToString("N2")
strConcatenatedInfo = strName.PadRight(40) &
strArtist.PadRight(25) & strPrice.PadLeft(5)
lstCds.Items.Add(strConcatenatedInfo)
End If
Next Name
End Sub
Private Sub btnRemove_Click(sender As Object, e As EventArgs) Handles btnRemove.Click
' removes the selected line from the list box
' if a line is selected, remove the line
If lstCds.SelectedIndex <> -1 Then
lstCds.Items.RemoveAt(lstCds.SelectedIndex)
End If
End Sub
End Class
Why not take advantage of the Using blocks? Make strNameCollection a List(Of String) instead of an array that you are not increasing it's size correctly.
Private strNameCollection As New List(Of String)
Using sr As New StreamReader("CDs.txt")
While Not sr.EndOfStream
strNameCollection.Add(sr.ReadLine)
End while
End Using ' file closed and stream disposed

Read Text File and Output Multiple Lines to a Textbox

I'm trying to read a text file with multiple lines and then display it in a textbox. The problem is that my program only reads one line. Can someone point out the mistake to me?
Imports System.IO
Imports Microsoft.VisualBasic.FileIO
Public Class Form1
Private BagelStreamReader As StreamReader
Private PhoneStreamWriter As StreamWriter
Dim ResponseDialogResult As DialogResult
Private Sub OpenToolStripMenuItem_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles OpenToolStripMenuItem.Click
'Dim PhoneStreamWriter As New StreamWriter(OpenFileDialog1.FileName)
'Is file already open
If PhoneStreamWriter IsNot Nothing Then
PhoneStreamWriter.Close()
End If
With OpenFileDialog1
.InitialDirectory = Directory.GetCurrentDirectory
.FileName = OpenFileDialog1.FileName
.Title = "Select File"
ResponseDialogResult = .ShowDialog()
End With
'If ResponseDialogResult <> DialogResult.Cancel Then
' PhoneStreamWriter = New StreamWriter(OpenFileDialog1.FileName)
'End If
Try
BagelStreamReader = New StreamReader(OpenFileDialog1.FileName)
DisplayRecord()
Catch ex As Exception
MessageBox.Show("File not found or is invalid.", "Data Error")
End Try
End Sub
Private Sub DisplayRecord()
Do Until BagelStreamReader.Peek = -1
TextBox1.Text = BagelStreamReader.ReadLine()
Loop
'MessageBox.Show("No more records to display.", "End of File")
'End If
End Sub
Private Sub SaveToolStripMenuItem_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles SaveToolStripMenuItem.Click
With SaveFileDialog1
.InitialDirectory = Directory.GetCurrentDirectory
.FileName = OpenFileDialog1.FileName
.Title = "Select File"
ResponseDialogResult = .ShowDialog()
End With
PhoneStreamWriter.WriteLine(TextBox1.Text)
With TextBox1
.Clear()
.Focus()
End With
TextBox1.Clear()
End Sub
Private Sub ExitToolStripMenuItem_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles ExitToolStripMenuItem.Click
Dim PhoneStreamWriter As New StreamWriter(OpenFileDialog1.FileName)
PhoneStreamWriter.Close()
Me.Close()
End Sub
End Class
Here is a sample textfile:
Banana nut
Blueberry
Cinnamon
Egg
Plain
Poppy Seed
Pumpkin
Rye
Salt
Sesame seed
You're probably only getting the last line in the file, right? Your code sets TextBox1.Text equal to BagelSteramReader.ReadLine() every time, overwriting the previous value of TextBox1.Text. Try TextBox1.Text += BagelStreamReader.ReadLine() + '\n'
Edit: Though I must steal agree with Hans Passant's commented idea on this; If you want an more efficient algorithm, File.ReadAllLines() even saves you time and money...though I didn't know of it myself. Darn .NET, having so many features...
I wrote a program to both write to and read from a text file. To write the lines of a list box to a text file I used the following code:
Private Sub txtWriteToTextfile_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtWriteToTextfile.Click
Dim FileWriter As StreamWriter
FileWriter = New StreamWriter(FileName, False)
' 3. Write some sample data to the file.
For i = 1 To lstNamesList.Items.Count
FileWriter.Write(lstNamesList.Items(i - 1).ToString)
FileWriter.Write(Chr(32))
Next i
FileWriter.Close()
End Sub
And to read and write the contents of the text file and write to a multi-line text box (you just need to set the multiple lines property of a text box to true) I used the following code. I also had to do some extra coding to break the individual words from the long string I received from the text file.
Private Sub cmdReadFromTextfile_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdReadFromTextfile.Click
Dim sStringFromFile As String = ""
Dim sTextString As String = ""
Dim iWordStartingPossition As Integer = 0
Dim iWordEndingPossition As Integer = 0
Dim iClearedTestLength As Integer = 0
Dim FileReader As StreamReader
FileReader = New StreamReader(FileName)
sStringFromFile = FileReader.ReadToEnd()
sTextString = sStringFromFile
txtTextFromFile.Text = ""
Do Until iClearedTestLength = Len(sTextString)
iWordEndingPossition = CInt(InStr((Microsoft.VisualBasic.Right(sTextString, Len(sTextString) - iWordStartingPossition)), " "))
txtTextFromFile.Text = txtTextFromFile.Text & (Microsoft.VisualBasic.Mid(sTextString, iWordStartingPossition + 1, iWordEndingPossition)) & vbCrLf
iWordStartingPossition = iWordStartingPossition + iWordEndingPossition
iClearedTestLength = iClearedTestLength + iWordEndingPossition
Loop
FileReader.Close()
End Sub