Null Reference Exception - Read from CSV - arrays

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.

Related

Moving file contents into an array

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 :)

ProcessWindowStyle.Hidden in string array

In my VB.net project, I am trying to call up multiple programs using an array to help clean up my code.
Currently, I have this code:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles StartServer.Click
Dim proc As New ProcessStartInfo()
Dim prochide As New ProcessStartInfo()
prochide.WindowStyle = ProcessWindowStyle.Hidden
If CheckBox1.CheckState = 1 Then
proc.WorkingDirectory = TextBox1.Text
proc.FileName = "xserver.exe"
Process.Start(proc)
proc.FileName = "yserver.exe"
Process.Start(proc)
proc.FileName = "zserver.exe"
Process.Start(proc)
Else
prochide.WorkingDirectory = TextBox1.Text
prochide.FileName = "xserver.exe"
Process.Start(prochide)
prochide.FileName = "yserver.exe"
Process.Start(prochide)
prochide.FileName = "zserver.exe"
Process.Start(prochide)
End If
End Sub
What this does is allows me to hide the windows so they show up in task manager but the windows don't actually show up.
However, I would prefer to switch with this code or something similar to clean it up:
Dim servers(0 To 2) As String
servers(0) = "xserver.exe"
servers(1) = "yserver.exe"
servers(2) = "zserver.exe"
Then I can simplify the code:
Dim directory As String = TextBox1.Text
For Each fileName As String In servers
Next
However, I cannot figure out how to hide the windows in an array, since the .WindowStyle = ProcessWindowStyle.Hidden does not seem to work with array strings. Is there another way I can do this?Changing the method is fine, I just want to try to clean up the code since it seems a bit bulky right now.
Okay so I've finally checked this out, and this works for me:
Public Class Form1
Dim servers() As String = New String() {"cmd.exe|1", "cmd.exe|1", "cmd.exe|1"}
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Dim directory As String = TextBox1.Text
Dim prochide As New ProcessStartInfo()
prochide.WorkingDirectory = directory
For Each fileName As String In servers
Dim FileOptions() As String = Split(fileName, "|")
prochide.FileName = FileOptions(0)
prochide.WindowStyle = CType(FileOptions(1), ProcessWindowStyle)
Process.Start(prochide)
Next
End Sub
End Class
When using New String() you cannot declare the array with a limit. So that was our problem. :)
So instead of Dim servers(3)... or Dim servers(0 To 2)... you have to use Dim servers()...

Visual Basic Issue getting listbox to populate from text file

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

Display value of selected array

I have a CSV file that is formatted as (name,number) on each line.
I'm creating an app that loads all names, index(0), into a listbox at form-load and when a name is selected the number, index(1), is displayed in a .textbox.
I start by filling an array and displaying index(0) in the box. No Prob. But when the selected text changes I have problems. If you cant tell I'm new to VB. If I could assign a var to the selected text I could use a while loop but I'm not sure how to assign that. Is there a better way to go about this? Below is my source. Any help would be great.
Public Class Form1
Public Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
For Each line As String In IO.File.ReadAllLines("MembershipPhone.txt")
Dim myData = line.Split(","c)
Dim mName = myData(0)
Dim mPhone = myData(1)
ListBox1.Items.Add(mName)
Next
End Sub
Private Sub ListBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ListBox1.SelectedIndexChanged
For Each line As String In IO.File.ReadAllLines("MembershipPhone.txt")
Dim query = line.Split(","c)
Dim mName = query(0)
Dim mPhone = query(1)
TextBox2.Text = mPhone
Next
End Sub

VB2010 Extract a string of numbers from a string or array

I have a filepath that I would like to pull the starting directory job number from the beginning of the filepath. Except I don't know how to just pull the number string out of the filepath string. (i.e.: filepath= Q:\2456_blah_blah\file.txt - or something) I'd like to just pull '2456' as a string,
then put that number string into TextBox2 I've created on my form.
The code I have so far spits out a '0' instead of the number string desired.
Any help would be much appreciated.
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Me.OpenFileDialog1.FileName = Nothing
If Me.OpenFileDialog1.ShowDialog = System.Windows.Forms.DialogResult.OK Then
Me.TextBox1.Text = Me.OpenFileDialog1.FileName
End If
If GetInfo() = True Then
For Each Xitem In ExcelRowList
Dim lvitem As ListViewItem
lvitem = Me.ListView1.Items.Add(Xitem.C1)
Next
End If
'''Here is where I call the GetFilePathOnly function
TextBox2.Text = GetFilePathOnly(TextBox1.Text)
End Sub
Private Sub TextBox1_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged
End Sub
'''Section below is what defines my number string, then I call it above for the Button1.Click operation(towards the end)
Private Function GetFilePathOnly(ByVal Fullpath As String) As String
Dim File As String = Fullpath
Dim number As Double = Val(File)
Dim outcome As String = number.ToString 'File.Substring(0, File.LastIndexOf("\") + 1)
Return outcome
End Function
Thanks
You could also use a regular expression easily.
Dim numRegex As New Regex("\d+")
Dim number As String = numRegex.Match("Q:\2456_blah_blah\file.txt").Value
A lazy way would be to use Split:
TextBox2.Text = path.Split("\")(1).Split("_")(0)

Resources