Listview multi lines - vb.net

I created a program to load a text file, should load all lines from the textfile and display them in the listview
However It only loads the first line in the listview how do I get it to read the entire file?
Sub Loadbtn_Click(sender As System.Object, e As System.EventArgs) Handles Browse.Click
OpenFD.ShowDialog()
Dim Path As String = OpenFD.FileName
Dim AllItems As String
Try
AllItems = My.Computer.FileSystem.ReadAllText(Path)
Dim ItemLines As New TextBox
ItemLines.Text = AllItems
Dim lv As New ListViewItem
For Each Line As String In ItemLines.Lines
List.Items.Add(lv)
lv.Text = Line
lv.SubItems.Add(Crypto.AES_Decrypt(Line))
Next
Catch ex As Exception
End Try
End Sub

One possible solution could look like this:
Sub Loadbtn_Click(sender As System.Object, e As System.EventArgs) Handles Browse.Click
OpenFD.ShowDialog()
' full path to the file + name
Dim filename As String = OpenFD.FileName
Try
' check if file exists to prevent errors
if (File.Exists(filename)) then
' fetch complete text into as lines
Dim Lines = File.ReadAllLines(filename)
' iterate over each line
For Each Line As String In Lines
Dim lv as new ListViewItem
' take it
lv.Text = Line
' and use it
lv.SubItems.Add(Crypto.AES_Decrypt(Line))
' show it
List.Items.Add(lv)
Next
end if
Catch ex As Exception
' inform the user resp. developer
Console.WriteLine(String.Format("An error occurred: {0}", ex.Message))
End Try
End Sub
As already mentioned use File.ReadAllLines if you want to read the file line by line and don't suppress errors - inform the user or at least the developer (yourself, using a log file or something appropriate).

Related

Error with VB ParseFileText method

When I run this I made a dummy "Button1" to test populate the fields they will successfully fill out the texts boxes. How ever I will have it parse that file every minute, and when I do it again I get the error shown below. By adding the routine "DisplayForm_Load" to the button1_click even it would work fine.
My question is I'm pretty sure I shouldn't have to redefine this every time? I think I'm not setting the index back to 0 or something along those lines. From what I've been able to understand from MS website is its like its indexing things in the array that don't exist.
Error received:
An unhandled exception of type 'System.IndexOutOfRangeException' occurred in WindowsApplication4.exe
Imports Microsoft.VisualBasic.FileIO
Public Class Form1
Private Directory As String ' Used to hold the folder directory to push/pull data from.
Private FileParser As Microsoft.VisualBasic.FileIO.TextFieldParser
Private Sub PushButton_Click(ByVal sender As Object, ByVal e As EventArgs) Handles PushButton.Click
' Sends information to txt file.
' This bit works fine, just writes code to txt file that can be parsed below.
End Sub
Sub DefineTextFieldParse_Load() Handles MyBase.Load
' Instantiate teh TextFieldParser and the set the delimiter
Dim FileName As String = "C:\Users\Caleb\Documents\TestDoc.txt"
Try
FileParser = New FileIO.TextFieldParser(FileName) '' Selects File to Parse
FileParser.TextFieldType = FieldType.Delimited
FileParser.SetDelimiters(",")
Catch ex As Exception
' Errors
MessageBox.Show("Unable to read the file" & "," & FileName)
End Try
End Sub
Sub UpdateCheck()
' Checks share txt file for update.
Dim FileName As String = "C:\Users\<Me>\Documents\TestDoc.txt"
Dim FieldString() As String
'Read the file
If Not FileParser.EndOfData Then
FieldString = FileParser.ReadFields()
' 1st Field
NIS1TextBox.Text = FieldString(0)
' 2nd Field
NIS2TextBox.Text = FieldString(1)
' You get the idea...All Testboxes identified above in the write section
' Repeats 12 more times...
EODTextBox.Text = FieldString(14)
InfoRichTextBox.Text = FieldString.LastOrDefault()
End If
End Sub
Sub PushUpdate()
End Sub
Private Sub Button1_Click_1(sender As Object, e As EventArgs) Handles Button1.Click
'DefineTextFieldParse_Load()_Load() ' When Enabled code works fine when commented out generates alert.
UpdateCheck()
End Sub
End Class
mchihinney - I did review https://msdn.microsoft.com/en-us/library/hks5e2k6.aspx
However what I found was the issue was with the formatting of the text file. The problem I found was with the text file there was a second line which was blank, so when it tried to parse nothing it through the error. Deleting the second line from the .txt file and worked as expected.

Import CSV file to database using VB

I need to import the information from a CSV txt file to a database using the DataGridView in my form. The application should allow the user to open a .txt file and then update the DataGridView table in my form. I am able to get the file, but am unable to update the grid using the file. I can update textboxes, but cannot figure out how to update the grid. Can anyone help me out with this?
Imports Microsoft.VisualBasic.FileIO
Imports System.IO
Public Class Form1
Private fileToOpen As String 'the file to be opened and read
Private responseFileDialog As DialogResult 'response from OpenFileDialog
Private myStreamReader As StreamReader 'the reader object to get contents of file
Private myStreamWriter As StreamWriter 'the writer object to save contents of textbox
Private myTextFieldParser As TextFieldParser ' To parse text to searched.
Dim myDataAdapter As OleDb.OleDbDataAdapter
Dim myString() As String
Dim myRow As DataRow
Private Sub PeopleBindingNavigatorSaveItem_Click(sender As Object, e As EventArgs) Handles PeopleBindingNavigatorSaveItem.Click
Me.Validate()
Me.PeopleBindingSource.EndEdit()
Me.TableAdapterManager.UpdateAll(Me.MyContactsDataSet)
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'MyContactsDataSet.People' table. You can move, or remove it, as needed.
Me.PeopleTableAdapter.Fill(Me.MyContactsDataSet.People)
End Sub
Private Sub OpenToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles OpenToolStripMenuItem.Click
Dim fileContentString As String 'contents of the file
Dim update As New OleDb.OleDbCommandBuilder(myDataAdapter)
'Dim myRow As DataRow
'set the properties of the OpenFileDialog object
OpenFileDialog1.InitialDirectory = My.Computer.FileSystem.CurrentDirectory
OpenFileDialog1.Title = "Select File to View..."
OpenFileDialog1.Filter = "Text Files (*.txt)|*.txt|All Files (*.*)|*.*"
'responseFileDialog contains holds the response of the user (which button they selected)
responseFileDialog = OpenFileDialog1.ShowDialog()
'check to see if the user select OKAY, if not they selected CANCEL so don't open anything
If (responseFileDialog <> System.Windows.Forms.DialogResult.Cancel) Then
'make sure there isn't a file already open, if there is then close it
If (myStreamReader IsNot Nothing) Then
myStreamReader.Close()
'TextBoxFileOutput.Clear()
End If
'open the file and read its text and display in the textbox
fileToOpen = OpenFileDialog1.FileName
myStreamReader = New StreamReader(OpenFileDialog1.FileName)
initTextFieldParser()
'loop through the file reading its text and adding it to the textbox on the form
Do Until myStreamReader.Peek = -1
fileContentString = myStreamReader.ReadLine()
'Try
' myTextFieldParser = New TextFieldParser(fileToOpen)
' myTextFieldParser.TextFieldType = FieldType.Delimited
' myTextFieldParser.SetDelimiters(",")
'Catch ex As Exception
' MessageBox.Show("Cannot Open File to Be Read!")
'End Try
myTextFieldParser.TextFieldType = FieldType.Delimited
myString = TextFieldParser.NewLine()
myRow.Item("FirstName") = myString(1)
MyContactsDataSet.Tables("People").Rows.Add(myRow)
PeopleTableAdapter.Update(MyContactsDataSet)
'TextBoxFileOutput.AppendText(fileContentString)
'TextBoxFileOutput.AppendText(Environment.NewLine)
Loop
'close the StreamReader now that we are done with it
myStreamReader.Close()
'SaveToolStripMenuItem.Enabled = True
End If
End Sub
Private Sub initTextFieldParser()
'Close myTextFieldParser in case the user is surfing through the records and then
'decides to search for a particular last name --> Basically start searching from beginning of the file
If (myTextFieldParser IsNot Nothing) Then
myTextFieldParser.Close()
End If
Try
myTextFieldParser = New TextFieldParser(fileToOpen)
myTextFieldParser.TextFieldType = FieldType.Delimited
myTextFieldParser.SetDelimiters(",")
Catch ex As Exception
MessageBox.Show("Cannot Open File to Be Read!")
End Try
End Sub
End Class
updating gridview with your file content
Import System.IO as we gonna need StreamReader
Using reader As New StreamReader("filepath")
DataGridView1.Columns.Add("col1",reader.ReadToEnd())
End Using
check this out!

Importing a CSV into a combobox, then changing other things in VB

What I want to do is import a CSV file (called fwlist.txt), that looks like this:
modelname,power type,pic,part number,firmware, option1, option 1, etc
End result, i would like a combobox that shows the modelname, and when the model name is selected from the pulldown, it updates various labels and text boxes on the form with other information.
Here's what I have so far:
Dim filename As String = "fwlist.txt"
Dim pwrtype As String
Dim pic As String
Dim partnum As String
Dim lineread As String
Dim FirmwareName As String
Private Sub ReadFirmwaresLoad(sender As Object, e As EventArgs) Handles Me.Load
' Load the items into the NameComboBox list.
Dim ResponseDialogResult As DialogResult
Try
Dim FirmwareStreamReader As StreamReader = New StreamReader(filename)
' Read all the elements into the list.
Do Until FirmwareStreamReader.Peek = -1
lineread = FirmwareStreamReader.ReadLine()
Dim fields As String() = lineread.Split(",")
FirmwareName = fields(0) 'Take First Field
cbFW.Items.Add(FirmwareName)
'Set Text labels based on position in line.
pwrtype = fields(1)
pic = fields(2)
partnum = fields(3)
(...etc through options)
Loop
' Close the file.
FirmwareStreamReader.Close()
Catch ex As Exception
' File missing.
ResponseDialogResult = MessageBox.Show("File not Found!", "File Not Found",
MessageBoxButtons.OK, MessageBoxIcon.Question)
If ResponseDialogResult = DialogResult.OK Then
' Exit the program.
Me.Close()
End If
End Try
End Sub
Private Sub cbFW_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cbFW.SelectedIndexChanged
lblPwrType.Text = pwrtype
lblPic.Text = pic
lblPartNum.Text = parnum
....etc thruogh options
End Sub
This code works, but only sort of. If i select anything from the combo box, it only gives me the information from the very last line of the CSV file - even if its the first entry in the box. I'm pretty sure it's something simple that I'm messing up.. anyone help?
First we read the lines into Firmware objects then we set this List(Of Firmware) as the DataSource of the ComboBox.
Then we handle the SelectedIndexChanged event of the ComboBox which will get the currently selected firmware and loads its data to the TextBox controls.
This is a tested, working example below:
Public Class Firmware
Public Property ModelName As String
Public Property PowerType As String
Public Property Pic As String
Public Property PartNumber As String
Public Property Firmware As String
Public Property Option1 As String
End Class
Public Class MainForm
Private Sub btnLoad_Click(sender As Object, e As EventArgs) Handles btnLoad.Click
Dim lines As String() = Nothing
Try
' Read the file in one step
lines = File.ReadAllLines("fwlist.txt")
Catch ex As Exception
Dim dialogResult As DialogResult = MessageBox.Show(Me, "File not found! Would you like to exit program?", "Error reading file", MessageBoxButtons.YesNo, MessageBoxIcon.Error, MessageBoxDefaultButton.Button2)
If dialogResult = DialogResult.Yes Then
Me.Close()
End If
Exit Sub
End Try
Dim firmwares As List(Of Firmware) = New List(Of Firmware)
For Each line As String In lines
Dim rawData As String() = line.Split({","}, StringSplitOptions.None)
' Create Firmware object from each line
Dim firmware As Firmware = New Firmware() With
{
.ModelName = rawData(0),
.PowerType = rawData(1),
.Pic = rawData(2),
.PartNumber = rawData(3),
.Firmware = rawData(4),
.Option1 = rawData(5)
}
' We store the read firmwares into a list
firmwares.Add(firmware)
Next
' Set the list as the data source of the combobox
' DisplayMember indicates which property will be shown in the combobox
With cboModelNames
.DataSource = firmwares
.DisplayMember = "ModelName"
End With
End Sub
Private Sub cboModelNames_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cboModelNames.SelectedIndexChanged
RefreshForm()
End Sub
Private Sub RefreshForm()
' Get the selected item as Firmware object
Dim currentFirmware As Firmware = DirectCast(cboModelNames.SelectedItem, Firmware)
' Refresh all the textboxes with the information
With currentFirmware
txtPowerType.Text = .PowerType
txtPic.Text = .Pic
txtPartNumber.Text = .PartNumber
txtFirmware.Text = .Firmware
txtOption1.Text = .Option1
End With
End Sub
End Class
Every time you set the value of a variable like pwrtype, its old value is thrown away and there is no way to get it back. And even if you did save multiple values for each variable, you would need a way to figure out which value goes with the currently selected item in the combo box. To resolve these two issues you need:
a way to group values from the same line together
a way to save all values read from the file, not just the most recent ones
Let's start with the first issue, grouping values together. In the example code below, I created a Structure type called FirmwareInfo to serve that purpose. Each FirmwareInfo has its own pwrtype, pic, etc.
The other piece of the puzzle that you are missing is a way to save more than one Firmware. The easiest way to do this is to add each FirmwareInfo to the combo box's item list, instead of adding just the display string. The combo box will convert each item to a string in the UI; the ToString() method tells it how you want this conversion to be done.
I haven't run this example code so I can't guarantee there aren't mistakes in there, but hopefully it's enough to show the general idea.
Dim filename As String = "fwlist.txt"
Structure FirmwareInfo
Public pwrtype As String
Public pic As String
Public partnum As String
Public FirmwareName As String
Public Overrides Function ToString() As String
Return FirmwareName
End Function
End Structure
Private Sub ReadFirmwaresLoad(sender As Object, e As EventArgs) Handles Me.Load
' Load the items into the NameComboBox list.
Dim ResponseDialogResult As DialogResult
Try
Dim FirmwareStreamReader As StreamReader = New StreamReader(filename)
' Read all the elements into the list.
Do Until FirmwareStreamReader.Peek = -1
Dim lineread = FirmwareStreamReader.ReadLine()
Dim fields As String() = lineread.Split(",")
Dim info As New FirmwareInfo With {
.FirmwareName = fields(0),
.pwrtype = fields(1),
.pic = fields(2),
.partnum = fields(3)
}
cbFW.Items.Add(info)
Loop
' Close the file.
FirmwareStreamReader.Close()
Catch ex As Exception
' File missing.
ResponseDialogResult = MessageBox.Show("File not Found!", "File Not Found",
MessageBoxButtons.OK, MessageBoxIcon.Question)
If ResponseDialogResult = DialogResult.OK Then
' Exit the program.
Me.Close()
End If
End Try
End Sub
Private Sub cbFW_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cbFW.SelectedIndexChanged
Dim currentInfo = DirectCast(cbFW.SelectedItem, FirmwareInfo)
lblPwrType.Text = currentInfo.pwrtype
lblPic.Text = currentInfo.pic
lblPartNum.Text = currentInfo.parnum
' ....etc through options
End Sub

How to work out if a file has been read in order to read the next file?

Here is my code:
Private Sub btnDisplayOrderDetails_Click(ByVal sender As Object, _
ByVal e As EventArgs) _
Handles btnDisplayOrder Details.Click
Dim myStreamReader As StreamReader
Try
myStreamReader = File.OpenText("Textfile1.txt")
Me.txtOrderDetails.Text = myStreamReader.ReadToEnd()
Catch exc As Exception
Finally
If Not myStreamReader Is Nothing Then
myStreamReader.Close()
End If
End Try
If txtOrderDetails.Text = "" Then
Dim mystreamreader1 As StreamReader
Try
mystreamreader1 = File.OpenText("textfile2.txt")
Me.txtOrderDetails.Text = myStreamReader.ReadToEnd()
Catch ex As Exception
Finally
If Not myStreamReader Is Nothing Then
mystreamreader1.Close()
End If
End Try
End If
End Sub
What I would like this code to do is:
Read the first Text file upon button click, then when I've cleared the text Box (with the use of a different button which is already coded) I would then like to read in the second text file upon button click into the same Text box as before.
It's not clear what you are trying to do with the files. Combine them all into a single text box, or does each file belong to a specific textbox.
The looping method to place all the files into a single text box:
Dim filePath As String = "C:\Users\Practice\Practice\bin\Debug"
Dim sb As New StringBuilder
For Each f As String In Directory.GetFiles(filePath, "*.txt")
sb.AppendLine(File.ReadAllText(f))
Next
txtOrderDetails.Text = sb.ToString()
Or if it's not a list, then you go through your files one by one:
Dim test1 As String = Path.Combine(filePath, "Textbox1.txt")
If File.Exists(test1) Then
TextBox1.Text = File.ReadAllText(test1)
End If
Dim test2 As String = Path.Combine(filePath, "Textbox2.txt")
If File.Exists(test2) Then
TextBox2.Text = File.ReadAllText(test2)
End If

Populating a combo box with the first word of a textfile

So I feel like im pretty close, but I also have a feeling I am mixing up StreamReader and ReadAllLines
....................................................................................
Option Strict On
Imports System.IO
Public Class Form4
Dim file As System.IO.StreamWriter
Private Sub Form4_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
file = My.Computer.FileSystem.OpenTextFileWriter("c:\devices.bat", False)
file.WriteLine("#echo off")
file.WriteLine("cd " & Form1.TextBox2.Text)
file.WriteLine("adb devices > C:\devices.txt")
file.Close()
Shell("C:\devices.bat", AppWinStyle.Hide, True, 500)
Dim output() = System.IO.File.ReadAllLines("C:\deviceinfo2.txt")
Dim Devices As String = ""
Dim line() As String = {}
For X = 1 To output.Count = -1
line = output(X).Split(New Char() {(" ")})
Devices = line(0)
ComboBox1.Items.Add(Devices)
Next
output.Close()
output.Dispose()
End Sub
End Class
........................................................................
What I am trying to have it do is to start reading on line two of devices.txt and then read the first word from each line until the text file is done.
It seems simple enough, but like I said, I think I am mixing streamreader with readalllines
Any help is appreciated
Class Test
Public Sub Main()
Try
' Create an instance of StreamReader to read from a file.
' The using statement also closes the StreamReader.
Using sr As New StreamReader("TestFile.txt")
Dim line, firstWord As String
Dim i as Integer = 0
' Read and display lines from the file until the end of
' the file is reached.
Do
line = sr.ReadLine()
If Not (line Is Nothing) AndAlso i > 0 Then
firstWord = line.Split(" ")(i)
'do your logic
End If
i += 1
Loop Until line Is Nothing
End Using
Catch e As Exception
' Let the user know what went wrong.
End Try
End Sub
End Class
Grabbed this from MSDN and modified it. It should compile, but I didn't test it. This will loop through the lines, 1 by 1, skip the first line and grab each line's first word after. Hope this helps.