Moving file contents into an array - arrays

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

Related

argument out of range parameter name index

since i have the code of the auto generated text box
Insert data from auto generated textbox to SQL Server database
i am try to write a code for ensuring of the auto generated text box in FlowLayoutPanel1 contain data
the auto generated text box build depends on the number in Val(Label2.Text) of the real part
and if any text box is null or empty then the process will stop until fill all fields
the auto generated text box will be like this if the Val(Label2.Text)
is equal to 3
so i try this in the save button
Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
For k As Integer = 1 To Val(Label2.Text)
If String.IsNullOrEmpty(FlowLayoutPanel1.Controls(i).Text) Then
MsgBox("Error , fill all text box")
Return
Else
UpdateUsers()
i += 1
End If
Next
MsgBox("Done , add all data to database ")
Button3.Enabled = False
End Sub
so i getting error after leave some text box and back to fill it again
and the all of form code is
Imports System.Data.SqlClient
'library for create folders
Imports System.IO
Public Class part
Dim cLeft As Integer = 1
Dim top1 As Integer = 5
Dim i As Integer = 0
Dim path1 As String
Dim cmd As SqlCommand
Public Sub AddNewTextBox()
Dim txt As New System.Windows.Forms.TextBox()
txt.Top = cLeft * 30
txt.Left = 100
'txt.Text = "TextBox " & Me.cLeft.ToString
cLeft = cLeft + 1
txt.ForeColor = Color.White
txt.BackColor = Color.Gray
txt.Font = New Font("Arial", 14.0, FontStyle.Regular)
txt.Size = New Size(350, 31)
txt.Location = New Point(156, 130 + top1)
txt.TextAlign = HorizontalAlignment.Center
FlowLayoutPanel1.Controls.Add(txt)
End Sub
Private Sub part_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'college part number
Label2.Visible = False
'college path folder
Label3.Visible = False
For m As Integer = 1 To Val(Label2.Text)
AddNewTextBox()
top1 = top1 + 35
Next
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Me.Close()
End Sub
Private Sub UpdateUsers()
Using cn As New SqlConnection("Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\Hazim M\Desktop\stud_project\stud_project\Database1.mdf;Integrated Security=True;User Instance=True")
Using cmd As New SqlCommand("INSERT INTO college_part ([name],[coll_of_part],[part_path]) Values (#name,#coll_of_part,#part_path);", cn)
If i < Val(Label2.Text) Then
path1 = Label3.Text & "\" & FlowLayoutPanel1.Controls(i).Text.Trim & Date.Now.Year
cmd.Parameters.Add("#name", SqlDbType.NVarChar).Value = FlowLayoutPanel1.Controls(i).Text
cmd.Parameters.Add("#coll_of_part", SqlDbType.NVarChar).Value = Label1.Text
cmd.Parameters.Add("#part_path", SqlDbType.NVarChar).Value = path1
cn.Open()
cmd.ExecuteNonQuery()
cn.Close()
If Not Directory.Exists(path1) Then
Directory.CreateDirectory(path1)
Else
MsgBox("folder is existing")
End If
End If
End Using
End Using
End Sub
Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
For k As Integer = 1 To Val(Label2.Text)
If String.IsNullOrEmpty(FlowLayoutPanel1.Controls(i).Text) Then
MsgBox("Error , fill all text box")
Return
Else
UpdateUsers()
i += 1
End If
Next
MsgBox("Done , add all data to database ")
Button3.Enabled = False
End Sub
End Class
thank u
I think you need to move dim i Integer=0 to local variable in the Button3_click method. ANd Pass i to the UpdateUser call (add the param to UpdateUser). The current global i keeps adding 1 and eventually out of range.

Reading CSV file into multiple arrays

If I wanted to read the following from a CSV file into 4 separate arrays how would I proceed?
Ex:
John,Doe,100,98
Jane,Smith,90,90
I need to take a student's First & Last Name. The first grade is their midterm, the second is their final.
Dim Name As String = ""
Dim inFile As StreamReader
Dim outFile As StreamWriter
inFile = File.OpenText("grades.csv")
outFile = File.CreateText("report.txt")
Do While (Not inFile.EndOfStream)
Name = CStr(inFile.ReadToEnd)
outFile.WriteLine(Name)
Loop
inFile.Close()
outFile.Close()
I see a million different ways to split things, I only output the file to see what I'm getting. Can someone help me split these into separate arrays? Thanks
Try this..... An example that might give you some ideas....
Imports System.Data.OleDb
Public Class Form1
Private dt As New DataTable
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim folder = "<Path to the folder of your grades.csv file (don't include the file name, just the path up to the folder)>"
Dim CnStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & folder & ";Extended Properties=""text;HDR=No;FMT=Delimited"";"
' in the next line replace grades.csv with the name of your file....
Using Adp As New OleDbDataAdapter("select F1 + ' ' + F2 as FirstSecondName, F3 as MidTerm, F4 as Final from [grades.csv] ", CnStr)
Try
Adp.Fill(dt)
Catch ex As Exception
End Try
End Using
Me.ListBox1.DataSource = dt
ListBox1.DisplayMember = "FirstSecondName"
ListBox1.ValueMember = "FirstSecondName"
AddHandler ListBox1.SelectedIndexChanged, AddressOf ListBox1_SelectedIndexChanged
End Sub
Private Sub ListBox1_SelectedIndexChanged(sender As Object, e As EventArgs)
Dim senderListBox As ListBox = sender
If senderListBox.SelectedIndex <> -1 Then
Dim SelectedData As DataRowView = senderListBox.SelectedItem
MessageBox.Show(String.Format("Selected - {0} :: Mid-Term Result = {1} :: Final Result = {2}", SelectedData("FirstSecondName").ToString, SelectedData("MidTerm").ToString, SelectedData("Final").ToString))
End If
End Sub
End Class

Writing contents of an array to a file VB

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

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

Null Reference Exception - Read from CSV

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.

Resources