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
Related
I'm trying to write the array persons to a file and read it and have no clue on how to go about it. Here's my code:
Public Class Form1
Structure Person
Public name As String
Public height As Integer
Public weight As Double
End Structure
Dim persons(49) As Person
Dim arraySize As Integer = 0
Private Sub submitBtn_Click(sender As Object, e As EventArgs) Handles submitBtn.Click
If arraySize < 50 Then
Dim Name As String
Dim Height As Integer
Dim Weight As Double
Name = nameTxt.Text
Height = CInt(heightTxt.Text)
Weight = CDbl(weightTxt.Text)
nameTxt.Text = Nothing
heightTxt.Text = Nothing
weightTxt.Text = Nothing
arraySize += 1
persons(arraySize).name = Name
persons(arraySize).height = Height
persons(arraySize).weight = Weight
Else
MsgBox("The list of people is full now. You may no longer enter new people.")
End If
End Sub
Private Sub saveBtn_Click(sender As Object, e As EventArgs) Handles saveBtn.Click
End Sub
Private Sub readBtn_Click(sender As Object, e As EventArgs) Handles readBtn.Click
End Sub
End Class
Any help on how to code this would be appreciated. Thank you!
I tried coding it to save the array persons (which is linked to the structure Person) to a file, but the app freezes, and i am not sure how to get around it.
try to use list :
Public Class Form1
<Serializable()> Structure Person
Public name As String
Public height As Integer
Public weight As Double
End Structure
dim persons As List(Of Person)
Private Sub submitBtn_Click(sender As Object, e As EventArgs) Handles submitBtn.Click
If persons.length < 50 Then
Dim Name As String
Dim Height As Integer
Dim Weight As Double
Name = nameTxt.Text
Height = CInt(heightTxt.Text)
Weight = CDbl(weightTxt.Text)
nameTxt.Text = Nothing
heightTxt.Text = Nothing
weightTxt.Text = Nothing
person.name = Name
person.height = Height
person.weight = Weight
persons.add(person)
Else
MsgBox("The list of people is full now. You may no longer enter new people.")
End If
End Sub
Private Sub saveBtn_Click(sender As Object, e As EventArgs) Handles saveBtn.Click
Using fs As New IO.FileStream("d:\backup\persons.dat", IO.FileMode.Create)
Dim formatter As New BinaryFormatter
formatter.Serialize(fs, persons)
End Using
End Sub
Private Sub readBtn_Click(sender As Object, e As EventArgs) Handles readBtn.Click
Using fs As New IO.FileStream("d:\backup\persons.dat", IO.FileMode.Open)
Dim formatter As New BinaryFormatter
persons = DirectCast(formatter.Deserialize(fs), List(Of person))
End Using
End Sub
dont forget to add <Serializable()> in front of struc definition.
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 :)
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()...
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
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.