Exporting CSV from ListView in VB.NET - vb.net

i am having a bit of issue with exporting my data from a List-view in VB.NET i have included screenshots of what i am seeing basically i want to see only the Values in my csv file when i export it,
as you can see i am seeing what the List-box is showing, those values are coming from the List View Before Export. also i need the export to be in 1 column not rows as shown
any help would be great..
''''
Imports System.IO
Imports System.IO.StreamReader
Imports System.IO.StreamWriter
Imports System.Data.DataSet
Public Class Form1
Private Sub startcol_Click(sender As Object, e As EventArgs) Handles startcol.Click
Timer1.Enabled = True
End Sub
Private Sub stopcol_Click(sender As Object, e As EventArgs) Handles stopcol.Click
Timer1.Enabled = False
End Sub
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
Const MIN As Double = 5.0
Const MAX As Double = 400.0
Const DEC_PLACES As Integer = 2
Dim rnd As New Random
Dim list As Integer()
'Generate a random number X where MIN <= X < MAX and then round to DEC_PLACES decimal places.
Dim dbl As Double = Math.Round(rnd.NextDouble() * (MAX - MIN) + MIN, DEC_PLACES)
weight.Text = dbl
Dim newItem As New ListViewItem(weight.Text)
newItem.SubItems.Add(weight.Text)
'newItem.SubItems.Add(TextBox3.Text)
ListBox1.Items.Add(newItem)
ListView1.Items.Add(newItem)
rowcnt.Text = ListView1.Items.Count
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Timer1.Enabled = True
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
' ExportDatasetToCsv(List)
'WriteToTextFile()
Me.DoSave()
End Sub
Private Sub DoSave()
Dim SFD As New SaveFileDialog()
Try
With SFD
.AddExtension = True
.CheckPathExists = True
.CreatePrompt = False
.OverwritePrompt = True
.ValidateNames = True
.ShowHelp = True
.DefaultExt = "txt"
.Filter = _
"CSV Files (*.csv)|*.csv|" & _
"All files|*.*"
.FilterIndex = 1
If .ShowDialog() = Windows.Forms.DialogResult.OK Then
Me.DoSaveItems(.FileName)
End If
End With
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Exclamation, Me.Text)
End Try
End Sub
' save All values from ListView1
Private Sub DoSaveItems(ByVal fileName As String)
If fileName Is Nothing = False Then
If fileName.Length > 0 Then
Using writer As New System.IO.StreamWriter(fileName)
For Each currentItem As Object In Me.ListView1.Items
writer.Write(currentItem.ToString() & ",")
Next
End Using
End If
End If
End Sub
Public Function ExportListViewToCSV(ByVal filename As String, ByVal lv As ListView) As Boolean
Try
' Open output file
Dim os As New StreamWriter(filename)
' Write Headers
For i As Integer = 0 To lv.Columns.Count - 1
' replace quotes with double quotes if necessary
os.Write("""" & lv.Columns(i).Text.Replace("""", """""") & """,")
Next
os.WriteLine()
' Write records
For i As Integer = 0 To lv.Items.Count - 1
For j As Integer = 0 To lv.Columns.Count - 1
os.Write("""" & lv.Items(i).SubItems(j).Text.Replace("""", """""") + """,")
Next
os.WriteLine()
Next
os.Close()
Catch ex As Exception
' catch any errors
Return False
End Try
Return True
End Function
Public Sub TestExportToCSV()
Dim dlg As New SaveFileDialog
dlg.Filter = "CSV files (*.CSV)|*.csv"
dlg.FilterIndex = 1
dlg.RestoreDirectory = True
If dlg.ShowDialog = Windows.Forms.DialogResult.OK Then
If ExportListViewToCSV(dlg.FileName, ListView1) Then
Process.Start(dlg.FileName)
End If
End If
End Sub
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
'TestExportToCSV()
End Sub
End Class
''''

As you haven't shown us your code, we can't tell you how to modify it specifically. In general though, you can treat the ListView somewhat like a 2D array, looping through the rows and the columns to get the data. That means that you could output the data to a CSV like this:
Using writer As New StreamWriter(filePath)
For rowIndex = 0 To myListView.Items.Count - 1
Dim item = myListView.Items(rowIndex)
'Write a line break before all but the first line.
If rowIndex > 0 Then
writer.WriteLine()
End If
For columnIndex = 0 To myListView.Columns.Count - 1
Dim subItem = item.SubItems(columnIndex)
'Write a field delimiter before all but the first field.
If columnIndex > 0 Then
write.Write(",")
End If
writer.Write(subItem.Text)
Next
Next
End Using
That's the old-school way. There are more succinct options, especially with the advent of LINQ:
File.WriteAllLines(filePath,
myListView.Items.
Cast(Of ListViewItem)().
Select(Function(item) String.Join(",",
item.SubItems.
Cast(Of ListViewItem.ListViewSubItem)().
Select(Function(subItem) subItem.Text))))
EDIT:
If you want to include the column headers then you can modify the above code like so:
Using writer As New StreamWriter(filePath)
For columnIndex = 0 To myListView.Columns.Count - 1
Dim column = myListView.Columns(columnIndex)
'Write a field delimiter before all but the first field.
If columnIndex > 0 Then
writer.Write(",")
End If
writer.Write(column.Text)
Next
For rowIndex = 0 To myListView.Items.Count - 1
Dim item = myListView.Items(rowIndex)
'Write a line break before each line.
writer.WriteLine()
For columnIndex = 0 To myListView.Columns.Count - 1
Dim subItem = item.SubItems(columnIndex)
'Write a field delimiter before all but the first field.
If columnIndex > 0 Then
writer.Write(",")
End If
writer.Write(subItem.Text)
Next
Next
End Using
File.WriteAllLines(filePath,
myListView.Items.
Cast(Of ListViewItem)().
Select(Function(item) String.Join(",",
item.SubItems.
Cast(Of ListViewItem.ListViewSubItem)().
Select(Function(subItem) subItem.Text))).
Prepend(String.Join(",",
myListView.Columns.
Cast(Of ColumnHeader)().
Select(Function(header) header.Text))))

Related

How to browse from bottom to top of a text file in vb.net?

I cannot get my code below to work correctly, in fact I want to press a back button in order to go up the lines one by one of a text file then I cut the chain into 3 parts.
Dim LinesOfText() As String = System.IO.File.ReadAllLines("c:\essai.librairie", Encoding.UTF8)
For line As Integer = LinesOfText.Length - 1 To 0 Step -1
Dim currentLine As String = LinesOfText(line)
Dim value As String = currentLine
Dim startIndex As Integer = 0
Dim length As Integer = 17
Dim substring As String = value.Substring(startIndex, length)
Dim subs As String = value.Substring(17, 90)
Dim subst As String = value.Substring(107, 120)
TextBox1.Text = substring
TextBox2.Text = subs
TextBox3.Text = subst
Next
If you store the lines and a line counter so that they are in scope where needed, you can do it like this:
Imports System.IO
Public Class Form1
Dim lines As String()
Dim currentLine As Integer = -1
Sub LoadData(filename As String)
lines = File.ReadAllLines(filename)
currentLine = lines.Length - 1
End Sub
Sub ShowCurrentLine()
If currentLine >= 0 Then
TextBox1.Text = lines(currentLine).Substring(0, 3)
TextBox2.Text = lines(currentLine).Substring(4, 3)
TextBox3.Text = lines(currentLine).Substring(8, 3)
lblLineNo.Text = (currentLine + 1) & "/" & lines.Length
Else
TextBox1.Clear()
TextBox2.Clear()
TextBox3.Clear()
lblLineNo.Text = "-"
End If
End Sub
Private Sub bnNext_Click(sender As Object, e As EventArgs) Handles bnNext.Click
If currentLine < lines.Length - 1 Then
currentLine += 1
ShowCurrentLine()
End If
End Sub
Private Sub bnPrev_Click(sender As Object, e As EventArgs) Handles bnPrev.Click
If currentLine > 0 Then
currentLine -= 1
ShowCurrentLine()
End If
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
LoadData("C:\temp\SO67209265.txt")
ShowCurrentLine()
End Sub
End Class
You will need to set the substring parameters for your data—I just used a small text file—and the filename to be loaded.
The label lblLineNo is used to show the current line number, starting at 1.

Score not being calculated correctly

Hi I'm created a program for a project and I've now started running some tests and the score for the user isn't being calculated correctly and I believe that it can't compare the answer given to the correct answer. I'm very confused and need any help that can be given. My code looks like this, any confusing parts and I'll try and explain.
Imports System.IO
Public Class QuestionScreen
Dim score As Integer = 0
Dim count As Integer
Dim Difficulty_ext As String
Dim questions, answers As New List(Of String)()
Private i As Integer
Sub ReadFile()
If Main.Diff_DDown.Text = "Easy" Then
Difficulty_ext = "questions - Easy"
ElseIf Main.Diff_DDown.Text = "Medium" Then
Difficulty_ext = "questions - Medium"
Else
Difficulty_ext = "questions - Difficult"
End If
Randomize()
Dim countline = File.ReadAllLines("c:\Users\Alice\Desktop\programme files\" & Difficulty_ext & ".txt").Length
Dim numline As Integer
Dim values() As String
Using sr As New StreamReader("c:\Users\Alice\Desktop\programme files\" & Difficulty_ext & ".txt")
While Not sr.EndOfStream
values = sr.ReadLine().Split(","c)
questions.Add(values(0))
answers.Add(values(1))
End While
End Using
numline = Int(Rnd() * countline)
For i As Integer = 0 To numline
Question.Text = questions(i)
Act_ANS.Text = answers(i)
Next
End Sub
Private Sub Pass_Btn_Click(sender As Object, e As EventArgs) Handles Pass_Btn.Click
If count < 10 Then
Call ReadFile()
count = count + 1
Ans_TxtBx.Text = ""
Hid_Score.Text = score
Else
ResultsScreen.Show()
Me.Hide()
End If
End Sub
Public Sub Submit_Btn_Click(sender As Object, e As EventArgs) Handles Submit_Btn.Click
If count < 10 Then
Call ReadFile()
count = count + 1
If Ans_TxtBx.Text = answers(i) Then
score = score + 1
End If
Hid_Score.Text = score
Else
ResultsScreen.Show()
Me.Hide()
count = 0
End If
Ans_TxtBx.Text = ""
End Sub
Private Sub QuestionScreen_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Call ReadFile()
End Sub
End Class
OK..... Try this, I have debugged your code trying to leave it pretty much as you had it, there were a number of problems, nothing major just a few lines of code in the wrong place....
Imports System.IO
Public Class Form1
Dim score As Integer = 0
Dim count As Integer
Dim Difficulty_ext As String
Dim questions, answers As New List(Of String)()
Private i As Integer
Sub ReadFile()
If Diff_DDown.Text = "Easy" Then
Difficulty_ext = "questions - Easy"
ElseIf Diff_DDown.Text = "Medium" Then
Difficulty_ext = "questions - Medium"
Else
Difficulty_ext = "questions - Difficult"
End If
Randomize()
Try
Dim countline = File.ReadAllLines("c:\Users\Alice\Desktop\programme files\" & Difficulty_ext & ".txt").Length
Dim numline As Integer
Dim values() As String
' clear the list of questions and answers
answers.Clear()
questions.Clear()
'''''''''''''''''''''''''''''''''''''''''
Using sr As New StreamReader("c:\Users\Alice\Desktop\programme files\" & Difficulty_ext & ".txt")
While Not sr.EndOfStream
values = sr.ReadLine().Split(","c)
questions.Add(values(0))
answers.Add(values(1))
End While
End Using
numline = Int(Rnd() * countline)
For i = 0 To numline
Question.Text = questions(i)
Act_ANS.Text = answers(i)
Next
Catch ex As Exception
End Try
End Sub
Private Sub Pass_Btn_Click(sender As Object, e As EventArgs) Handles Pass_Btn.Click
If count < 10 Then
count = count + 1
Ans_TxtBx.Text = ""
Hid_Score.Text = score
Else
ResultsScreen.Show()
Me.Hide()
End If
Call ReadFile() ' move this to the bottom
End Sub
Public Sub Submit_Btn_Click(sender As Object, e As EventArgs) Handles Submit_Btn.Click
If count < 10 Then
count = count + 1
If Ans_TxtBx.Text = answers(i - 1) Then ' need to subtract 1 here
score = score + 1
End If
Hid_Score.Text = score
Else
ResultsScreen.Show()
Me.Hide()
count = 0
End If
Ans_TxtBx.Text = ""
Call ReadFile() ' move this to the bottom
End Sub
Private Sub QuestionScreen_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Call ReadFile()
End Sub
End Class

looping to add 271 records into my dictionary it only add 150 then exit the subroutine. (VB.net 2015)

For VB.net 2015
I'm a new programmer. I've been warping my brain around this for 2 days. Can seem to see the problem. It seems I can only add 150 records to the dictionary. I'm not sure where its failing in the code. I'm not getting any errors or warnings.
Really hope someone can give me a hand.
Heres a link to my file I'm working with.
https://drive.google.com/file/d/0B1zf86jcRv49Y1lCMHRvNWt4UFk/view?usp=sharing
P.S. Sry about the crappy coding skill :-)
Imports System
Imports System.IO
Public Class Form1
Dim xx As Integer = 0
Private MainDataList As New Dictionary(Of String, List(Of String))
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim temp1 As List(Of String)
'MsgBox(xx)
If MainDataList.ContainsKey(TextBox1.Text) Then
temp1 = MainDataList.Item(TextBox1.Text)
Label1.Text = temp1(0)
Beep()
Else
Label1.Text = "Not Found"
Beep()
Beep()
End If
TextBox1.Text = ""
End Sub
Private Sub GetData()
Dim ReadDataLine(50000) As String
Try
' Open the file using a stream reader.
Using sr As New StreamReader("C:\Inventory\Invatory.csv")
'Dim line As String
' Read the stream to a string and write the string to the console.
ReadDataLine(0) = sr.ReadLine
Do While (sr.EndOfStream = False)
ReadDataLine(xx) = sr.ReadLine
'AddToList(ReadDataLine) ' pars data into main list
'MsgBox(sr.ReadLine)
xx = xx + 1
Loop
sr.Close()
'line = sr.ReadLine()
End Using
Catch e As Exception
'MsgBox(xx)
MsgBox("The file could not be read:")
MsgBox(e.Message)
End Try
'MsgBox(xx)
'xx = 0
For Each i As String In ReadDataLine
AddToList(i)
'MsgBox(xx)
'xx = xx + 1
Next
End Sub
Private Sub AddToList(data As String)
Dim barCode As String = ""
Dim steps As Integer = 1
Dim LastPos As Integer = 2
Dim datalist As New List(Of String)
Dim firstPass As Boolean = False
For i = 2 To Len(data)
'Find end of cell
If Mid(data, i, 1) = "," Then
If firstPass = False Then
barCode = Mid(data, LastPos, i - 2)
'MsgBox(Mid(data, LastPos, i - 2))
LastPos = i
firstPass = True
Else
Dim temp As Integer = i - LastPos
datalist.Add(Mid(data, LastPos + 1, temp - 1))
'MsgBox(Mid(data, LastPos + 1, temp - 1))
LastPos = i
End If
End If
Next
MainDataList.Add(barCode, datalist)
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
GetData()
Label1.Text = "Ready!"
Me.Show()
TextBox1.Focus()
End Sub
Private Sub Label1_Click(sender As Object, e As EventArgs) Handles Label1.Click
End Sub
End Class

VB.NET Read .Txt File Into Multiple Text Boxes

I have a program that I can enter in names and integer values in the text boxes and then save those to a file. That works perfectly fine but the part I need help with is the reading of the file.
The data is saved into the file much like a csv file. example:
Test, 5, 5, 5
dadea, 5, 5, 5
das, 5, 5, 5
asd, 5, 5, 5
dsadasd, 5, 5, 5
My problem is, how do I read that into multiple text boxes on my form?
The names (first value of each row) should go into their corresponding Name textbox (i.e. txtName0, txtName1, txtName2, etc.) and the integer values should also go into their corresponding text boxes (txtCut1, txtColour1, etc.).
I have spent the past 2 hours trying to figure this out but I just cant.
The part I need help with is the last method.
Imports System.IO
Public Class Form1
Private aPricesGrid(,) As TextBox
Private aAverages() As TextBox
Private aNames() As TextBox
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
aPricesGrid = {{txtCut1, txtColour1, txtUpDo1, txtHighlight1, txtExtensions1},
{txtCut2, txtColour2, txtUpDo2, txtHighlight2, txtExtensions2},
{txtCut3, txtColour3, txtUpDo3, txtHighlight3, txtExtensions3},
{txtCut4, txtColour4, txtUpDo4, txtBHighlight4, txtExtensions4},
{txtCut5, txtColour5, txtUpDo5, txtHighlight5, txtExtensions5}}
aAverages = {txtAvg0, txtAvg1, txtAvg2, txtAvg3, txtAvg4}
aNames = {txtName0, txtName1, txtName2, txtName3, txtName4}
End Sub
Private Sub btnCalculate_Click(sender As Object, e As EventArgs) Handles btnCalculate.Click
For nCol As Integer = 0 To 4
Dim nColTotal As Integer = 0
Dim nColItems As Integer = 0
For nRow As Integer = 0 To 2
Try
nColTotal += aPricesGrid(nRow, nCol).Text
nColItems += 1
Catch ex As Exception
End Try
Next
aAverages(nCol).Text = (nColTotal / nColItems).ToString("c")
Next
End Sub
Private Sub btnClear_Click(sender As Object, e As EventArgs) Handles btnClear.Click
For Each txt As Control In Me.Controls
If TypeOf txt Is TextBox Then
txt.Text = String.Empty
End If
Next
End Sub
Private Sub SaveToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles SaveToolStripMenuItem.Click
Dim oSaveFileDialog As New SaveFileDialog()
'Display the Common file Dialopg to user
oSaveFileDialog.Filter = "Text Files (*.txt)|*.txt"
If oSaveFileDialog.ShowDialog() = Windows.Forms.DialogResult.OK Then
' Retrieve Name and open it
Dim fileName As String = oSaveFileDialog.FileName
Dim outputFile As StreamWriter = File.CreateText(fileName)
For nRow As Integer = 0 To 4
outputFile.Write(aNames(nRow).Text)
For nCol As Integer = 0 To 2
outputFile.Write(", " & aPricesGrid(nRow, nCol).Text)
Next
outputFile.WriteLine()
Next
outputFile.Close()
End If
End Sub
Private Sub btnExit_Click(sender As Object, e As EventArgs) Handles btnExit.Click
Me.Close()
End Sub
Private Sub ReadToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles ReadToolStripMenuItem.Click
Dim oOpenFileDialog As New OpenFileDialog()
'Display the Common file Dialopg to user
oOpenFileDialog.Filter = "Text Files (*.txt)|*.txt"
If oOpenFileDialog.ShowDialog() = Windows.Forms.DialogResult.OK Then
Dim fileName As String = oOpenFileDialog.FileName
Dim OpenFile As StreamReader = File.OpenText(fileName)
End If
End Sub
End Class
Try this method.
Dim mindex as integer
Dim string1 as string()
Dim OpenFile As StreamReader = File.OpenText(fileName)
While OpenFile .Peek <> -1
string1= OpenFile .ReadLine.Split(",")
If mindex = 0 Then
txtname1.text=string1(0)
txtcut1.text=string1(1)
txtcolour1.text=string1(2)
'add other textboxes
ElseIf mindex = 1 Then
txtname2.text=string1(0)
txtcut2.text=string1(1)
txtcolour2.text=string1(2)
'add other textboxes
ElseIf mindex = 2 Then
txtname3.text=string1(0)
txtcut3.text=string1(1)
txtcolour3.text=string1(2)
'add other textboxes
ElseIf mindex = 3 Then
'your code
ElseIf mindex = 4 Then
'your code
End If
mindex += 1
End While
OpenFile .Close()
hope this helps.

Binary Reader and allowed characters

I have a problem.
Now program working like this:
Reading binary file bytes. &H1E and &H1F Allowed characters only :A123456789
If in file is B or C or D or E or F....... textbox1 = bad file
That's working. Now I want to add verification in &H10.
Allowed characters only 26
If other characters textbox1 = bad file
Imports System.IO
Imports System.IO.SeekOrigin
Public Class Form1
Dim charactersAllowed As String = "A123456789"
Dim swap As String = "26"
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim OFD As New OpenFileDialog
Dim fullFile() As Byte
With OFD
.Filter = "Binary files (*.bin)|*.bin"
End With
If OFD.ShowDialog = Windows.Forms.DialogResult.OK Then
fullFile = File.ReadAllBytes(OFD.FileName)
TextBox1.AppendText(fullFile(&H1E).ToString("X2") & " ")
TextBox1.AppendText(fullFile(&H1F).ToString("X2"))
TextBox4.AppendText(fullFile(&H10).ToString("X2"))
End If
Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
Dim theText As String = TextBox1.Text
Dim Letter As String
Dim SelectionIndex As Integer = TextBox1.SelectionStart
Dim Change As Integer
For x As Integer = 0 To TextBox1.Text.Length - 1
Letter = TextBox1.Text.Substring(x, 1)
If charactersAllowed.Contains(Letter) = False Then
theText = theText.Replace(Letter, String.Empty)
Change = 1
End If
Next
TextBox1.Text = theText
TextBox1.Select(SelectionIndex - Change, 0)
End Sub
Private Sub TextBox4_TextChanged(sender As Object, e As EventArgs) Handles TextBox4.TextAlignChanged
Dim check As String = TextBox4.Text
Dim check2 As String
Dim check3 As Integer = TextBox4.SelectionStart
Dim check4 As Integer
For x As Integer = 0 To TextBox4.Text.Length - 1
check2 = TextBox4.Text.Substring(x, 1)
If swap.Contains(check2) = False Then
check = check.Replace(check2, String.Empty)
check4 = 1
End If
Next
TextBox1.Text = check
TextBox1.Select(check3 - check4, 0)
End Sub
Hard to decode, but an obvious approach is to prevent editing when the byte has the wrong value:
If OFD.ShowDialog = Windows.Forms.DialogResult.OK Then
fullFile = File.ReadAllBytes(OFD.FileName)
If fullFile(&H10) <> 26 Then
TextBox1.Text = "Bad file"
TextBox1.Enabled = False
TextBox4.Enabled = False
Else
TextBox1.Enabled = True
TextBox4.Enabled = True
'' etc...
End If
End If