Visual Basic Sequential Access Files - vb.net

I've been working on this assignment for quite awhile, but I'm practically ripping my hair out. Before anyone jumps the gun and says I'm looking for a free handout on the assignment, please note, I've done 90% of the assignment! The program has 4 commercials in a list, you choose which one to vote for and it saves your vote and tallies it. As it tallies it in the program, it also saves it into a file. The next time you open the file, you can hit "Display vote" and it reads the file and re-tally's everything for the user.
Here's what the program looks like, at least what I have done. My issue is that when I hit display votes, nothing happens. It doesn't read in anything from the file. I tested using a message box for it to see if it displays anything from the file, and it does infact display the first item from the project. Anyone have any ideas?!
Public Class frmMain
Dim intVotes(3) As Integer
Private Sub frmMain_Load(sender As Object, e As EventArgs) Handles MyBase.Load
lstCom.Items.Add("Budweiser")
lstCom.Items.Add("FedEx")
lstCom.Items.Add("E*Trade")
lstCom.Items.Add("Pepsi")
lstCom.SelectedIndex = 0
End Sub
Private Sub btnSaveVote_Click(sender As Object, e As EventArgs) Handles btnSaveVote.Click
Dim outFile As IO.StreamWriter
Dim intSub As Integer
intSub = lstCom.SelectedIndex
If intSub <= intVotes.GetUpperBound(0) Then
intVotes(intSub) += 1
If IO.File.Exists("CallerVotes.txt") Then
outFile = IO.File.CreateText("CallerVotes.txt")
If lstCom.SelectedIndex = 0 Then
outFile.WriteLine("Budweiser")
ElseIf lstCom.SelectedIndex = 1 Then
outFile.WriteLine("FedEx")
ElseIf lstCom.SelectedIndex = 2 Then
outFile.WriteLine("E*TRADE")
ElseIf lstCom.SelectedIndex = 3 Then
outFile.WriteLine("Pepsi")
End If
outFile.Close()
End If
End If
lblBud.Text = intVotes(0).ToString
lblFed.Text = intVotes(1).ToString
lblET.Text = intVotes(2).ToString
lblPep.Text = intVotes(3).ToString
End Sub
Private Sub ListBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles lstCom.SelectedIndexChanged
End Sub
Private Sub btnExit_Click(sender As Object, e As EventArgs) Handles btnExit.Click
Me.Close()
End Sub
Private Sub btnDisplayVote_Click(sender As Object, e As EventArgs) Handles btnDisplayVote.Click
Dim inFile As IO.StreamReader
Dim strText As String
If IO.File.Exists("CallerVotes.txt") Then
inFile = IO.File.OpenText("CallerVotes.txt")
Do Until inFile.Peek = -1
strText = inFile.ReadLine
If strText = "Budweiser" Then
intVotes(0) += 1
ElseIf strText = "FedEx" Then
intVotes(1) += 1
ElseIf strText = "E*TRADE" Then
intVotes(2) += 1
ElseIf strText = "Pepsi" Then
intVotes(3) += 1
End If
Loop
inFile.Close()
End If
End Sub
End Class

If you look at your file I think you will see that you have only one entry. You are overwriting the file each time you click the save button by using the CreateText method.
from MSDN(emphasis mine)
This method is equivalent to the StreamWriter(String, Boolean) constructor overload with the append parameter set to false. If the file specified by path does not exist, it is created. If the file does exist, its contents are overwritten.
try using the AppendText method instead.
i.e.
If IO.File.Exists("CallerVotes.txt") Then
outFile = IO.File.AppendText("CallerVotes.txt")
You will also need to assign the values that you read in to the appropriate labels per DeanOC's answer.

I think that your problem is that you are not assigning the values from the intVotes array to the labels. At the end of btnDisplayVote_Click try adding
lblBud.Text = intVotes(0).ToString
lblFed.Text = intVotes(1).ToString
lblET.Text = intVotes(2).ToString
lblPep.Text = intVotes(3).ToString

Related

Importing data from text file in VB.NET

So, I am trying to develop a book database. I have created a table with 11 columns which populates a DGV, where only 6 columns are showed. The full data of each book is shown in a lower part of the form, where I have textboxes, which are bounded (BindingSource) to the table, that change as I move in the DGV.
Now, what I want to do is to have the posibility to export/import data from a file.
I have accomplished the exporting part with the following code:
Private Sub BtnExport_Click(sender As Object, e As EventArgs) Handles BtnExport.Click
Dim txt As String = String.Empty
For Each row As DataGridViewRow In DbdocsDataGridView.Rows
For Each cell As DataGridViewCell In row.Cells
'Add the Data rows.
txt += CStr(cell.Value & ","c)
Next
'Add new line.
txt += vbCr & vbLf
Next
Dim folderPath As String = "C:\CSV\"
File.WriteAllText(folderPath & "DataGridViewExport.txt", txt)
End Sub
However, I can't manage to import from the txt. What I've tried is this: https://1bestcsharp.blogspot.com/2018/04/vb.net-import-txt-file-text-to-datagridview.html
It works perfectly if you code the table and it populates de DGV without problem. I can't see how should I adapt that code to my need.
Private Sub BtnImport_Click(sender As Object, e As EventArgs) Handles BtnImport.Click
DbdocsDataGridView.DataSource = table
Dim filas() As String
Dim valores() As String
filas = File.ReadAllLines("C:\CSV\DataGridViewExport.txt")
For i As Integer = 0 To filas.Length - 1 Step +1
valores = filas(i).ToString().Split(",")
Dim row(valores.Length - 1) As String
For j As Integer = 0 To valores.Length - 1 Step +1
row(j) = valores(j).Trim()
Next j
table.Rows.Add(row)
Next i
End Sub
That is what I've tried so far, but I always have an exception arising.
Thanks in advance to anyone who can give me an insight about this.
The DataTable class has built-in methods to load/save data from/to XML called ReadXml and WriteXml. Take a look at example which uses the overload to preserve the schema:
Private ReadOnly dataGridViewExportPath As String = IO.Path.Combine("C:\", "CSV", "DataGridViewExport.txt")
Private Sub BtnExport_Click(sender As Object, e As EventArgs) Handles BtnExport.Click
table.WriteXml(path, XmlWriteMode.WriteSchema)
End Sub
Private Sub BtnImport_Click(sender As Object, e As EventArgs) Handles BtnImport.Click
table.ReadXml(path)
End Sub
While users can manually edit the XML file that is generated from WriteXML, I would certainly not suggest it.
This is code which writes to a text file:
speichern means to save.
Note that I use a # in my example for formatting reasons. When reading in again, you can find the # and then you know that and that line is coming...
And I used Private ReadOnly Deu As New System.Globalization.CultureInfo("de-DE") to format the Date into German format, but you can decide yourself if you want that. 🙂
Note that I'm using a FileDialog that I downloaded from Visual Studio's own NuGet package manager.
Private Sub Button_speichern_Click(sender As Object, e As EventArgs) Handles Button_speichern.Click
speichern()
End Sub
Private Sub speichern()
'-------------------------------------------------------------------------------------------------------------
' User can choose where to save the text file and the program will save it .
'-------------------------------------------------------------------------------------------------------------
Dim Path As String
Using SFD1 As New CommonSaveFileDialog
SFD1.Title = "store data in a text file"
SFD1.Filters.Add(New CommonFileDialogFilter("Textdatei", ".txt"))
SFD1.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
If SFD1.ShowDialog() = CommonFileDialogResult.Ok Then
Path = SFD1.FileName & ".txt"
Else
Return
End If
End Using
Using textfile As System.IO.StreamWriter = My.Computer.FileSystem.OpenTextFileWriter(Path, True, System.Text.Encoding.UTF8)
textfile.WriteLine("Timestamp of this file [dd.mm.yyyy hh:mm:ss]: " & Date.Now.ToString("G", Deu) & NewLine & NewLine) 'supposed to be line break + 2 blank lines :-)
textfile.WriteLine("your text")
textfile.WriteLine("#") 'Marker
textfile.Close()
End Using
End Sub
Private Sub FormMain_FormClosing(sender As Object, e As FormClosingEventArgs) Handles MyBase.FormClosing
speichern()
End Sub
And this is to read from a text file:
'read all Text
Dim RAT() As String = System.IO.File.ReadAllLines(Pfad, System.Text.Encoding.UTF8)
If RAT.Length = 0 Then Return Nothing
For i As Integer = 0 To RAT.Length - 1 Step 1
If RAT(i) = "#" OrElse RAT(i) = "" Then Continue For
'do your work here with (RAT(i))
Next

How do I use VB Application.DoEvent?

I have a process that works well when it's running against small files but gives an "Message=Managed Debugging Assistant 'ContextSwitchDeadlock' : 'The CLR has been unable to transition from COM context 0xa5b8e0 to COM context 0xa5b828 for 60 seconds." error when running against large files. I'm pretty new to VB and did some investigating and found that using Application.DoEvent seemed to be recommended. I was hoping that someone could show me an example of how to use that. If I'm executing a Sub called "Process1", how would I use the DoEvent to prevent it from timing out. Ideally I'd like to add a progress bar as well but I have ot idea on that one either. I'd appreciate any help. Please keep it simple as I'm new to VB/VS.
This is the comment from my first question showing the code. Process1 calls a sub named ArchDtlCopyFile1 which scrolls through the values in a list view, copying the files named in the items to a different location. It then calls ArchDtlCheckCopy1 to scroll through the list view again to ensure that the copy was done. It then decides if the source file should be deleted and do it if required. Finally it inserts a row in an Access table documenting the change made.
Private Sub Process1()
If ReturnCode = 0 Then
ArchDtlCopyFile1()
Else
' MessageBox.Show("Error code coming in is: " & CStr(ReturnCode))
End If
If ReturnCode = 0 Then
ArchDtlCheckCopy1()
Else
' MessageBox.Show("Error code for check copy is: " & CStr(ReturnCode))
End If
End Sub
Private Sub ArchDtlCopyFile1()
intLVIndex = 0
' Copy the file from the source computer onto the NAS
Do While intLVIndex < intMaxFileIndex
Try
' Select the row from the LVFiles ListView, then move the first column (0) into strSourceFilePath and the last
' column (3) into strDestFilePath. Execute the CopyFile method to copy the file.
LVFiles.Items(intLVIndex).Selected = True
strSourceFilePath = LVFiles.SelectedItems(intLVIndex).SubItems(0).Text
strDestFilePath = LVFiles.SelectedItems(intLVIndex).SubItems(3).Text
My.Computer.FileSystem.CopyFile(strSourceFilePath, strDestFilePath, overwrite:=False)
Catch ex As Exception
' Even if there's an error with one file, we should continue trying to process the rest of the files
Continue Do
End Try
intLVIndex += 1
Loop
End Sub
Private Sub ArchDtlCheckCopy1()
intLVIndex = 0
intLVError = 0
' ' Check each file was copied onto the NAS
Do While intLVIndex < intMaxFileIndex
' Select the row from the LVFiles ListView, then move the last column (3) into strDestFilePath.
' Use the FileExists method to ensure the file was created on the NAS. If it was, call the
' ADetDelete Sub to delete the source file from the user's computer.
LVFiles.Items(intLVIndex).Selected = True
strSourceFilePath = LVFiles.SelectedItems(intLVIndex).SubItems(0).Text
strDestFilePath = LVFiles.SelectedItems(intLVIndex).SubItems(3).Text
strSourceFile = LVFiles.SelectedItems(intLVIndex).SubItems(1).Text
Try
If My.Computer.FileSystem.FileExists(strDestFilePath) Then
' Archive file was created so go ahead and delete the source file
'If strSourceFile = myCheckFile Then
' strDestFile = LVFiles.SelectedItems(intLVIndex).SubItems(3).Text
'End If
If RBArchive.Checked = True Then
ArchDtlDeleteFile(strSourceFilePath)
End If
PrepareDtlVariables()
ADtlAddRow()
Else
MessageBox.Show("File not found. " & strDestFilePath)
End If
Catch ex As Exception
ErrorCode = "ARC6"
MessageCode = "Error while checking file copy"
ReturnCode = 8
End Try
intLVIndex += 1
Loop
End Sub
Here's a simplified example:
Imports System.ComponentModel
Imports System.IO
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
BackgroundWorker1.WorkerReportsProgress = True
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Button1.Enabled = False
BackgroundWorker1.RunWorkerAsync()
End Sub
Private Sub BackgroundWorker1_DoWork(sender As Object, e As DoWorkEventArgs) Handles BackgroundWorker1.DoWork
For i As Integer = 1 To 20
BackgroundWorker1.ReportProgress(i) ' you can pass anything out using the other overloaded ReportProgress()
System.Threading.Thread.Sleep(1000)
Next
End Sub
Private Sub BackgroundWorker1_ProgressChanged(sender As Object, e As ProgressChangedEventArgs) Handles BackgroundWorker1.ProgressChanged
' you can also use e.UserState to pass out ANYTHING
Label1.Text = e.ProgressPercentage
End Sub
Private Sub BackgroundWorker1_RunWorkerCompleted(sender As Object, e As RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted
MessageBox.Show("Done!")
Button1.Enabled = True
End Sub
End Class

Play different MP3 files one by one in VB.Net 2019

I am creating a small forms application in VB.Net 2019 that will scan my harddrive for MP3 files and then play them in random order.
At this moment I scan my disk and load everything in two listboxes (one for the path, one for the filename because I also want to export in CSV). Somewhere in the future this data will go in a database with extra information so I can choose the genre of music I want to randomly play at that moment.
When I click my cmdRandom commandbutton, the first file starts to play but when I want to continue with the next random file, the file is searched and loaded into media player but doesn't start playing (I have to click "play" manually).
Here's my code:
Private Sub cmdRandom_Click(sender As Object, e As EventArgs) Handles cmdRandom.Click
intaantal = ListBox2.Items.Count
Randomize()
PlayMedia()
End Sub
Private Sub PlayMedia()
intNumber = CInt(Int((intAantal * Rnd()) + 1))
ListBox1.SelectedIndex = intNumber
ListBox2.SelectedIndex = intNumber
FileName = ListBox1.SelectedItem.ToString() + "\" + ListBox2.SelectedItem.ToString()
lblSongText.Text = FileName
' mPlayer.URL = ""
' mPlayer.Refresh()
' mPlayer.close()
' mPlayer.settings.autoStart = True
' mPlayer.settings.setMode("loop", True)
' mPlayer.Ctlcontrols.play()
mPlayer.URL = FileName
End Sub
Private Sub mPlayer_PlayStateChange(sender As Object, e As _WMPOCXEvents_PlayStateChangeEvent) Handles mPlayer.PlayStateChange
If mPlayer.playState = mPlayer.playState.wmppsMediaEnded Then
PlayMedia()
End If
End Sub
All items in PlayMedia() that are commented out have already been tested but don't work. I thought that adding mPlayer.Ctlcontrols.play() in the mPlayer_playStateChange () function in an else clause of the current if would work but that gives me a compilation error (seems to not be allowed in this event).
What am I doing wrong?
Found the sollution on the web after another search: (https://social.msdn.microsoft.com/Forums/sqlserver/en-US/31082234-7161-4446-a96e-32c0314dfe0f/actions-when-a-media-player-control-finished-playing?forum=vbgeneral). It all has to do with the time between the end of the first song and the loading of the next.
I added a timer and things are fixed now, I set the timer interval to 100.
Private Sub mPlayer_PlayStateChange(sender As Object, e As _WMPOCXEvents_PlayStateChangeEvent) Handles mPlayer.PlayStateChange
If mPlayer.playState = mPlayer.playState.wmppsMediaEnded Then
mPlayer.Ctlcontrols.stop()
Timer1.Start()
End If
End Sub
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
Timer1.Stop()
PlayMedia()
End Sub

Getting strings from a textfile in a combobox, vb.net

Here is my code :
I'm trying to have some value out from a TXT file to a combobox or label but i feel combobox would be easier.
here's my code :
please note, some config.txt will only have 1 value while other 5-6
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim IDinFile As String
Dim ID As String
If IO.File.Exists("config.txt") Then
Using StreamReader As New IO.StreamReader("config.txt")
Do
IDinFile = StreamReader.ReadLine
If (IDinFile.IndexOf("7656")) <> -1 Then
ID = IDinFile.Substring(2)
ID = ID.Trim().Remove(ID.Length - 1)
ComboBox1.Items.Add(ID)
Exit Do
End If
Loop Until IDinFile Is Nothing
End Using
End If
End Sub
the file here in .png :
https://i.stack.imgur.com/iYaqP.png
Re-written the code for you. Problem was wrongly placed Exit Do. Also, its advisable to check the line before entering the loop rather than at the end of the loop.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim IDinFile As String
Dim ID As String
Const FILENAME As String = "config.txt"
If IO.File.Exists(FILENAME) Then
Using StreamReader As New IO.StreamReader(FILENAME)
Do While StreamReader.Peek() >= 0
IDinFile = StreamReader.ReadLine.Trim()
If (IDinFile.IndexOf("7656")) <> -1 Then
ID = IDinFile.Substring(1, IDinFile.Length - 2)
ComboBox1.Items.Add(ID)
End If
Loop
End Using
End If
End Sub
After you add the first item to the combobox you have an Exit Do statement. It no longer continues checking further lines and adding them to the combobox.
You should remove that statement.
Try this. It'll work if the values are organized line by line in the txt file.
Dim srd as New StreamReader("config.txt")
If io.file.exists("config.txt") then
Dim str() = srd.ReadToEnd.split(environment.newline)
For i = 0 to str.count-1
Combobox.item.add(str(i))
Next
srd.close

HI, New to programming with textfiles loops and much more

i have a textfile which is in this format
and i am trying to use a stream reader to help me loop each word into a text box, i am new to programming and really need help because all other examples are too complicated for me to understand,
this is what i am trying to do :
Dim objectreader As New StreamReader("filepath")
Dim linereader(1) As String
linereader = Split(objectreader.ReadLine, ",")
For i As Integer = 0 To UBound(linereader)
Spelling_Test.txtSpelling1.Text = linereader(0)
Spelling_Test.txtSpelling2.Text = linereader(0)
Next
but only get the first line of the text file in to a textbox, i need it to loop to the next line so i can write the next line in!
your help would be much appreciated, and if possible then can you show it practically , if you dont understand what i am trying to do then please ask
It is a little confusing on what you are trying to do, it looks like your text file consists of a word and a hint, you only have one set of textbox's and 3 lines of information in your file.
This example show you how to incrementally read your Stream.
Public Class Form1
Dim objectreader As StreamReader
Dim linereader() As String
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
If IsNothing(objectreader) Then
objectreader = New StreamReader("C:\Temp\data.txt")
End If
linereader = Split(objectreader.ReadLine, ",")
If String.IsNullOrEmpty(linereader(0)) Then
objectreader.Close()
objectreader = Nothing
Else
txtSpelling1.Text = linereader(0) 'Word
txtSpelling2.Text = linereader(1) 'Hint
End If
End Sub
End Class
But in your case, I would probably just use the File.ReadAllLines Method
Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click
Dim result As String() = File.ReadAllLines("C:\Temp\data.txt")
For x = 0 To UBound(result)
Dim c As Control = Controls.Find("txtSpelling" + (x + 1).ToString, True)(0)
If Not IsNothing(c) Then
c.Text = Split(result(x), ",")(0)
End If
Next
End Sub