I am trying to write my contents of my array to a file. Its an array as a structure. I seem to be having an issue. I can't seem to read the file after it has been written. The app freezes up and if I check to see if my txt file has any info in it, it locks up as well.
Option Strict On
Option Explicit On
Option Infer Off
Public Class Form1
Structure Person
Public strName As String
Public dblHeight As Double
Public dblWeight As Double
End Structure
Private peopleDescription(49) As Person
Dim count As Integer = 0
Private Sub btnSubmit_Click(sender As Object, e As EventArgs) Handles btnSubmit.Click
If count <= 49 Then
peopleDescription(count).strName = txtName.Text
Double.TryParse(txtHeight.Text, peopleDescription(count).dblHeight)
Double.TryParse(txtWeight.Text, peopleDescription(count).dblWeight)
count += 1
End If
txtName.Text = String.Empty
txtHeight.Text = String.Empty
txtWeight.Text = String.Empty
txtName.Focus()
End Sub
Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
Dim outFile As IO.StreamWriter
Dim intC As Integer
outFile = IO.File.AppendText("persons.txt")
Do While intC < count
outFile.WriteLine(peopleDescription(intC))
Loop
outFile.Close()
End Sub
Private Sub btnRead_Click(sender As Object, e As EventArgs) Handles btnRead.Click
Dim inFile As IO.StreamReader
Dim strInfo As String
If IO.File.Exists("persons.txt") Then
inFile = IO.File.OpenText("persons.txt")
Do Until inFile.Peek = -1
strInfo = inFile.ReadLine
Loop
inFile.Close()
lblMessage.Text = strInfo
Else
MessageBox.Show("Can't find the persons.txt file", "Person Data", MessageBoxButtons.OK, MessageBoxIcon.Information)
End If
End Sub
End Class
I don't know what I am missing. If anyone can help I would appreciate it.
You fail to initialize intC before starting the while loop, and you're not incrementing it within the loop, so it never changes to exit it (presuming it gets inside the loop in the first place), which would make it seem to "lock up".
Set it to a starting value first, before you use it.
Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
Dim outFile As IO.StreamWriter
Dim intC As Integer = 0
outFile = IO.File.AppendText("persons.txt")
Do While intC < count
outFile.WriteLine(peopleDescription(intC))
intC += 1
Loop
outFile.Close()
End Sub
Related
Im currently working on getting this piece of code to work so that I can read a text file, move the contents into an array and then display a certain column (such as price)
Imports System.IO
Public Class Form1
Dim FileName As String
Dim i As Integer = 0
Dim Alpha As Integer = 0
Dim Products(31) As String
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
FileName = "Products.txt"
End Sub
Private Sub btnCreateArray_Click(sender As Object, e As EventArgs) Handles btnCreateArray.Click
Using MyReader As New Microsoft.VisualBasic.FileIO.TextFieldParser("Products.txt")
MyReader.TextFieldType = FileIO.FieldType.Delimited
MyReader.SetDelimiters(",")
Dim currentRow As String()
While Not MyReader.EndOfData
currentRow = MyReader.ReadFields()
Dim currentField As String
For Each currentField In currentRow
'MsgBox(currentField)
'txtShowNo.Text = currentField
'txtShowP.Text = i
i = i + 1
Products(i) = currentField
Next
End While
End Using
Do While Alpha <= i
If InStr((txtFileSearch.Text), (Products(Alpha))) Then
lstDisplayFile.Items.Add(Products(Alpha))
Alpha = Alpha + 1
End If
Loop
End Sub
Private Sub btn_Click(sender As Object, e As EventArgs) Handles btn.Click
txtFileSearch.Text = ""
End Sub
Private Sub btnAddToFilePrintFile_Click(sender As Object, e As EventArgs) Handles btnAddToFilePrintFile.Click
Dim Name As String
Dim SName As String
Dim IDNo As Integer
Name = txtName.Text
SName = txtSName.Text
IDNo = txtIDNo.Text
FileOpen(1, FileName, OpenMode.Append) ' create a new empty file & open it in append mode'
WriteLine(1, IDNo, Name, SName) ' Writes a line of data'
FileClose(1)
txtName.Text = ""
txtSName.Text = ""
txtIDNo.Text = ""
txtName.Focus()
End Sub
End Class
The program crashes on this line of code:
lstDisplayFile.Items.Add(Products(Alpha))
along with the following message :
An unhandled exception of type 'System.ArgumentNullException' occurred in System.Windows.Forms.dll
Alpha is my counter, and my thought process behind this was that if the input within the textbox is currently in the array, it will display the completed text in the array.
Here is the current contents within my text file :
"£5.00","50"
"£2.50","30"
If anyone could help me solve this I would be appreciative :)
I am stuck and have tried re-writing my code multiple times and cannot figure out a solution. The application has a text file containing items and prices in a sequential access file. The app should display the price corresponding with the item when it is selected from the list box. Each line in the text file contains the item's number followed by a comma and then the price.
I need to define a structure named item. The structure has 2 member variables, a string to store the item number and a decimal storing the price. I also need to declare a class level array with 5 item structure variables. The load even should read the items and prices and store this info in the class-level array. Then it should add the item numbers to the list box.
This is what I have so far but nothing is working.
Option Explicit On
Option Strict On
Option Infer Off
Public Class frmMain
'declare structure with 2 member variables
Structure Item
Public strItemNum As String
Public decPrice As Decimal
End Structure
'declare array for 5 item structure variables
Private items(4) As Item
Private Sub btnExit_Click(sender As Object, e As EventArgs) Handles btnExit.Click
Me.Close()
End Sub
Private Sub frmMain_Load(sender As Object, e As EventArgs) Handles Me.Load
'declare variables
Dim inFile As IO.StreamReader
Dim strLineofText As String
Dim intSub As Integer
'check if the file exists
If IO.File.Exists("ItemInfo.txt") Then
'open the file
inFile = IO.File.OpenText("ItemInfo.txt")
'read the file
Do Until inFile.Peek = -1 OrElse
intSub = items.Length
strLineofText = inFile.ReadLine.Trim
'add item to list box
lstNumbers.Items.Add(items(intSub).strItemNum)
Loop
'close the file
inFile.Close()
Else
MessageBox.Show("Can't find the ItemInfo.txtfile",
"Kensington Industries",
MessageBoxButtons.OK,
MessageBoxIcon.Information)
End If
End Sub
Private Sub lstNumbers_SelectedIndexChanged(sender As Object, e As EventArgs) Handles lstNumbers.SelectedIndexChanged
lblPrice.Text = items(lstNumbers.SelectedIndex).decPrice.ToString("C2")
End Sub
End Class
I think that you need to change the name of Structure. Item can be used in another references.
Try to change the name to itemstr (for example)
Do Until inFile.Peek = -1 OrElse
intSub = items.Length
strLineofText = inFile.ReadLine.Trim
'add item to list box
Dim arr As String() = str.Split(","C)
Dim valitem As New itemstr()
valitem.text = arr(0)
valitem.value = Convert.ToDecimal(arr(1))
lstNumbers.Items.Add(valitem)
Loop
Thanks everyone. I ended up starting over again and trying something different that works finally!
Option Explicit On
Option Strict On
Option Infer Off
Public Class frmMain
'declare structure
Structure Item
Public strItemNum As String
Public decPrice As Decimal
End Structure
'declare class level array
Public itemList(4) As Item
Private Sub btnExit_Click(sender As Object, e As EventArgs) Handles btnExit.Click
Me.Close()
End Sub
Private Sub frmMain_Load(sender As Object, e As EventArgs) Handles Me.Load
'declare variables
Dim inFile As IO.StreamReader
Dim strLineOfText As String
Dim decPrice As Decimal
Dim strInfo(4, 1) As String
'check to see if the file exists
If IO.File.Exists("ItemInfo.txt") Then
'open the file
inFile = IO.File.OpenText("ItemInfo.txt")
For intRow As Integer = 0 To strInfo.GetUpperBound(0)
'read the line
strLineOfText = inFile.ReadLine
'assign substring from comma to first coloumn
strInfo(intRow, 0) = strLineOfText.Substring(0, strLineOfText.IndexOf(","))
Dim intSep As Integer = strLineOfText.IndexOf(",") + 1
'assign substring after comma to 2nd column
strInfo(intRow, 1) = strLineOfText.Substring(intSep)
'assign first column value to strItemNum variable
itemList(intRow).strItemNum = (strInfo(intRow, 0))
Decimal.TryParse(strInfo(intRow, 1), decPrice)
'assign 2nd columnn value to decPrice variable
itemList(intRow).decPrice = decPrice
'add item to listbox
lstNumbers.Items.Add(itemList(intRow).strItemNum)
Next intRow
'clost the file
inFile.Close()
Else
'error message if file cannot be found
MessageBox.Show("Can't find the ItemInfo.txtfile",
"Kensington Industries",
MessageBoxButtons.OK,
MessageBoxIcon.Information)
End If
End Sub
Private Sub lstNumbers_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs) Handles lstNumbers.SelectedIndexChanged
'display the price
lblPrice.Text = itemList(lstNumbers.SelectedIndex).decPrice.ToString("C2")
End Sub
End Class
Hello this is my first time posting here. well to the point, I have pieced together
a app that is able to load a text file, add on the fly to a "listbox", now all i need it to Ping all ips in said "listbox" but i get an error and stops working. need help to ping all ips.
Private Sub Go_Click(sender As Object, e As EventArgs) Handles Go.Click
If ListBox1.Items.Count <= 0 Then
MsgBox("Please Add at Least One IP or Website!")
Exit Sub
End If
For l_index As Integer = 0 To ListBox1.Items.Count - 1 'THIS IS WHERE CODE STOPS WORKING, NEED "MAGIC CODE" HERE
Dim lines As String = CStr(ListBox1.Items(l_index))
BackgroundWorker1.RunWorkerAsync(lines)
Next
End Sub
I am using Openfiledialog to load Text File to listbox1 and backgroundworker to do the ping. I am using
Imports System.Net
Imports System.Net.NetworkInformation
Imports System.Threading
Imports System.IO
What i want to do is once that all "IPs" are in the listbox i want to press Go to Ping all Ips. How can i get this to work?
Imports System.Net
Imports System.Net.NetworkInformation
Imports System.Threading
Imports System.IO
Public Class Main
Private Sub AboutUpingToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles AboutUpingToolStripMenuItem.Click
AboutUping.Show()
End Sub
Private Sub MenuStrip1_ItemClicked(sender As Object, e As ToolStripItemClickedEventArgs) Handles MainMenu.ItemClicked
End Sub
Private Sub QuitToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles QuitToolStripMenuItem.Click
Application.Exit()
End Sub
Private Sub OpenFileDialog1_FileOk(sender As Object, e As System.ComponentModel.CancelEventArgs) Handles OpenFileDialog1.FileOk
Dim lines = File.ReadAllLines(OpenFileDialog1.FileName)
ListBox1.Items.AddRange(lines)
End Sub
Private Sub OpenToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles OpenToolStripMenuItem.Click
OpenFileDialog1.ShowDialog()
End Sub
Private Sub NewToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles NewToolStripMenuItem.Click
Create.Show()
End Sub
Private Sub ToolStripMenuItem1_Click(sender As Object, e As EventArgs) Handles ToolStripMenuItem1.Click
End Sub
Private Sub Main_Load(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
Private Sub Go_Click(sender As Object, e As EventArgs) Handles Go.Click
If ListBox1.Items.Count <= 0 Then
MsgBox("Please Add at Least One IP or Website!")
Exit Sub
End If
For l_index As Integer = 0 To ListBox1.Items.Count - 1 'THIS IS WHERE CODE STOPS WORKING, NEED "MAGIC CODE" HERE
Dim lines As String = CStr(ListBox1.Items(l_index))
BackgroundWorker1.RunWorkerAsync(lines)
Next
End Sub
Private Sub CloseFileToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles CloseFileToolStripMenuItem.Click
TextBox1.Clear()
ListBox1.Items.Clear()
End Sub
Private Sub cmdADD_Click(sender As Object, e As EventArgs) Handles cmdADD.Click
Dim myitem
myitem = txtADD.Text()
ListBox1.Items.Add(myitem)
txtADD.Clear()
End Sub
Private Sub cmdRemove_Click(sender As Object, e As EventArgs) Handles cmdRemove.Click
For a As Int32 = ListBox1.SelectedItems.Count - 1 To 0 Step -1
For i As Int32 = ListBox1.Items.Count - 1 To 0 Step -1
'-- compare the value of the select item to any given item in the list.
If ListBox1.SelectedItems(a) = ListBox1.Items(i) Then
'-- remove the item by the index we found
ListBox1.Items.RemoveAt(i)
'-- exit the inner for loop
Exit For
End If
Next
Next
End Sub
Private Sub cmdClear_Click(sender As Object, e As EventArgs) Handles cmdClear.Click
ListBox1.Items.Clear()
End Sub
Private Sub HelpToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles HelpToolStripMenuItem.Click
End Sub
Private Sub ListBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ListBox1.SelectedIndexChanged
End Sub
Private Sub BackgroundWorker1_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
Dim lines = DirectCast(e.Argument, String())
Dim Ping As New Ping
Dim replies As New List(Of PingReply)
For Each ip In lines
Dim reply = Ping.Send(ip)
replies.Add(reply)
Next
e.Result = replies
End Sub
Private Sub BackgroundWorker1_RunWorkerCompleted(ByVal sender As Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted
Dim sb As New System.Text.StringBuilder
Dim replies = DirectCast(e.Result, List(Of PingReply))
For Each reply In replies
Dim index As Integer
index += 1
sb.Append("Ping ").Append(index).Append(": ").Append(reply.Address).Append(" ").Append(reply.RoundtripTime).Append(" ms")
sb.AppendLine()
Next
TextBox1.Text = sb.ToString
End Sub
End Class
Your error is here
one of your ping fails and results an exception which is returned to the completed event handler and when the handler tries to get the result the TargetInvocationException exception is thrown
solution is to check the error
Private Sub BackgroundWorker1_RunWorkerCompleted(ByVal sender As Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted
If e.Error Is Nothing Then
Dim sb As New System.Text.StringBuilder
Dim replies = DirectCast(e.Result, List(Of PingReply))
For Each reply In replies
Dim index As Integer
index += 1
sb.Append("Ping ").Append(index).Append(": ").Append(reply.Address).Append(" ").Append(reply.RoundtripTime).Append(" ms")
sb.AppendLine()
Next
TextBox1.Text = sb.ToString
Else
'error handling
End If
End Sub
additionally you may need to handle the actual error to protect rest of the ping replies otherwise because of 1 failure whole batch of result will be lost
For Each ip As String In lines
Try
Dim reply As PingReply = Ping.Send(ip)
replies.Add(reply)
Catch ex as PingException
'error handling
End Try
Next
Update
another point of error,
For l_index As Integer = 0 To ListBox1.Items.Count - 1
Dim lines As String = CStr(ListBox1.Items(l_index))
BackgroundWorker1.RunWorkerAsync(lines)
Next
since you are passing as single string from the method above and in the method below you are attempting to cast as string array so it fails, change it like this
Private Sub BackgroundWorker1_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
Dim ip = DirectCast(e.Argument, String)
Dim Ping As New Ping
Dim replies As New List(Of PingReply)
Try
Dim reply As PingReply = Ping.Send(ip)
replies.Add(reply)
Catch ex as PingException
'error handling
End Try
e.Result = replies
End Sub
also advised to use Option Strict On to reduce some type checking errors
Thanks!Got it to work! Sending "Listbox1" to array
Private Sub Go_Click(sender As Object, e As EventArgs) Handles Go.Click
Dim lines() As String = ListBox1.Items.OfType(Of String)().ToArray()
BackgroundWorker1.RunWorkerAsync(lines)
End Sub
Now it works app does not crash.
For some odd reason I am getting an error when I am using my loop to display the elements of my array. I can't seem to understand what it is I am doing or not doing right. This is the code so far. This is not for a class, I am learning myself.
Option Strict On
Option Explicit On
Option Infer Off
Public Class Form1
Private strExams(49, 2) As String
Dim count As Integer = 0
Private Sub btnAdd_Click(sender As Object, e As EventArgs) Handles btnAdd.Click
Dim strStudent As String = txtStudent.Text
Dim strTest As String = txtTest.Text
Dim strScore As String = txtScore.Text
If count <= 49 Then
strExams(count, 0) = strStudent
strExams(count, 1) = strTest
strExams(count, 2) = strScore
count += 1
End If
txtStudent.Text = String.Empty
txtTest.Text = String.Empty
txtScore.Text = String.Empty
txtStudent.Focus()
End Sub
Private Sub btnDisplay_Click(sender As Object, e As EventArgs) Handles btnDisplay.Click
Dim intHighRow As Integer = strExams.GetUpperBound(0)
Dim intHighCol As Integer = strExams.GetUpperBound(1)
Dim intR As Integer
Dim intC As Integer
Do While intC <= intHighCol
intR = 0
Do While intR <= intHighRow
lstMessage.Items.Add(strExams(intR, intC))
intR += 1
Loop
intC += 1
Loop
End Sub
This is the error I am getting when I click my display button.
An unhandled exception of type 'System.ArgumentNullException' occurred in System.Windows.Forms.dll
Additional information: Value cannot be null.
Try this. This makes much more sense to me. The reason you're getting a null error is that you haven't filled everything up in your array and your listbox can't list null items. So a workaround would be to enumerate only items that already have values, thus, just loop until the last value of count.
Private Sub btnDisplay_Click(sender As Object, e As EventArgs) Handles btnDisplay.Click
Dim intR As Integer
lstMessage.Items.Clear()
Do While intR < count
lstMessage.Items.Add(strExams(intR, 0) & " - " & strExams(intR, 1) & " - " & strExams(intR, 2))
intR += 1
Loop
End Sub
I have to code a WPF application for college which reads from a csv file. I get a null reference exception when I want to output the parts of the CSV lines into arrays. You can find the line where the error happens in commentary. Here is the code.
Imports System.Windows.Forms
Imports System.IO
Imports System.Globalization
Class MainWindow
Private foldername As String
Private arrGemeenten As String()
Private arrOppervlakte As Double()
Private arrInwoners As Integer()
Private arrDeelgemeenten As Integer()
Private Sub cboProvincie_SelectionChanged(ByVal sender As System.Object, ByVal e As System.Windows.Controls.SelectionChangedEventArgs) Handles cboProvincie.SelectionChanged
CSVInlezen()
End Sub
Private Sub MainWindow_Loaded(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles Me.Loaded
FileBrowserAanmaken()
comboBoxVullen()
End Sub
Private Sub comboBoxVullen()
For Each file As String In IO.Directory.GetFiles(foldername)
If file.EndsWith(".csv") Then
Dim filenaam As String = System.IO.Path.GetFileNameWithoutExtension(file)
cboProvincie.Items.Add(filenaam)
End If
Next
End Sub
Private Sub FileBrowserAanmaken()
'folderbrowserdialog aanmaken
Dim fbd As New FolderBrowserDialog
fbd.SelectedPath = AppDomain.CurrentDomain.BaseDirectory
' Show the FolderBrowserDialog.
Dim result As DialogResult = fbd.ShowDialog()
If (result = Forms.DialogResult.OK) Then
foldername = fbd.SelectedPath
End If
End Sub
Private Sub CSVInlezen()
Dim filepath As String = foldername & "\" & cboProvincie.SelectedValue & ".csv"
If File.Exists(filepath) Then
fileInlezenHulpMethode(filepath)
End If
End Sub
Private Sub fileInlezenHulpMethode(ByVal path As String)
'declarations
Dim sr As New StreamReader(path)
Dim iTeller As Integer = 0
Dim arrLijn As String()
Dim culture As New System.Globalization.CultureInfo("nl-BE")
'eerste lijn meteen uitlezen, dit zijn kolomkoppen en hebben we niet nodig
'read out first line, these are titles and we don't need them
sr.ReadLine()
Do While sr.Peek <> -1
Dim lijn As String = sr.ReadLine()
arrLijn = lijn.Split(";")
arrGemeenten(iTeller) = Convert.ToString(arrLijn(0)) 'HERE I GET THE ERROR!
arrOppervlakte(iTeller) = Double.Parse(arrLijn(2), NumberStyles.AllowDecimalPoint, culture.NumberFormat)
arrInwoners(iTeller) = Integer.Parse(arrLijn(3), NumberStyles.Integer Or NumberStyles.AllowThousands, culture.NumberFormat)
arrDeelgemeenten(iTeller) = Convert.ToString(arrLijn(4))
Loop
End Sub
End Class
You haven't created the array, you have only created a reference for it. To create the array you need to specify a size, for example:
Private arrGemeenten As String(100)
However, to specify the size, you need to know the size when you create the array. (Well, actually you put all data in the first item, so just the size 1 would keep it from crashing, but I don't thing that's what you intended.) You probably want to use lists instead:
Private gemeenten As New List(Of String)()
Then you use the Add method to add items to the list:
gemeenten.Add(Convert.ToString(arrLijn(0)))
Also, consider putting the data in a single list of a custom object, instead of having several lists of loosely coupled data.