VB2010 read a csv in datagrid, update in grid and save to same csv - vb.net

Created a procedure in VB2010 to read a csv-file in datagridviewer, update cells in grid and save to same csvfile
Opening the csvfile in the datagridviewer works fine,
Updating in the datagridviewer works fine also
But when I save the datagrid to a csv-file with the same name, I get an error message "The process Can not access the file because it is used by an other process".
But if I save it to an other filename it is ok.
Then I tried to copy the new file with the new filename back to the original filename.
I received still the same error message that I cant copy because the file is still in use.
Does anybody now how to solve this.
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim fName As String = ""
OpenFileDialog1.InitialDirectory = "H:\Data\2014\Software\VB2010\"
OpenFileDialog1.Filter = "CSV files (*.csv)|*.CSV"
OpenFileDialog1.FilterIndex = 2
OpenFileDialog1.RestoreDirectory = True
If (OpenFileDialog1.ShowDialog() = Windows.Forms.DialogResult.OK) Then
fName = OpenFileDialog1.FileName
End If
Me.TextBox1.Text = fName
Dim TextLine As String = ""
Dim SplitLine() As String
DataGridView1.ColumnCount = 5
DataGridView1.Columns(0).Name = "Name"
DataGridView1.Columns(1).Name = "Gender"
DataGridView1.Columns(2).Name = "Age"
DataGridView1.Columns(3).Name = "Ranking"
DataGridView1.Columns(4).Name = "Date"
If System.IO.File.Exists(fName) = True Then
Dim objReader As New System.IO.StreamReader(fName)
Do While objReader.Peek() <> -1
TextLine = objReader.ReadLine()
SplitLine = Split(TextLine, ",")
Me.DataGridView1.Rows.Add(SplitLine)
Loop
Else
MsgBox("File Does Not Exist")
End If
End Sub
Private Sub SaveGridDataInFile(ByRef fName As String)
'method called by button2
Dim I As Integer = 0
Dim j As Integer = 0
Dim cellvalue$
Dim rowLine As String = ""
Try
Dim objWriter As New System.IO.StreamWriter(fName, True)
For j = 0 To (DataGridView1.Rows.Count - 2)
For I = 0 To (DataGridView1.Columns.Count - 1)
If Not TypeOf DataGridView1.CurrentRow.Cells.Item(I).Value Is DBNull Then
cellvalue = DataGridView1.Item(I, j).Value
Else
cellvalue = ""
End If
rowLine = rowLine + cellvalue + ","
Next
objWriter.WriteLine(rowLine)
rowLine = ""
Next
objWriter.Close()
objWriter = Nothing
MsgBox("Text written to file")
Catch e As Exception
MessageBox.Show("Error occured while writing to the file." + e.ToString())
Finally
FileClose(1)
End Try
Call copy_file()
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
'çall method SaveGridDataInFile
SaveGridDataInFile(Me.TextBox1.Text)
' FileCopy("H:\Data\2014\Software\VB2010\datagr_ex2.csv", "H:\Data\2014\Software\VB2010\datagr_ex.csv")
End Sub
Sub copy_file()
Dim FileToDelete As String
FileToDelete = "H:\Data\2014\Software\VB2010\datagr_ex.csv"
If System.IO.File.Exists(FileToDelete) = True Then
System.IO.File.Delete(FileToDelete)
MsgBox("File Deleted")
End If
FileCopy("H:\Data\2014\Software\VB2010\datagr_ex2.csv", "H:\Data\2014\Software\VB2010\datagr_ex.csv")
End Sub

My guess is you need to close the StreamReader you use to load the file before you can reopen the file to save it. The StreamReader class implements IDisposable so you can use VB.Net's Using Statement to automatically close the file when you're finished reading, i.e.
If System.IO.File.Exists(fName) = True Then
Using objReader As New System.IO.StreamReader(fName)
Do While objReader.Peek() <> -1
TextLine = objReader.ReadLine()
SplitLine = Split(TextLine, ",")
Me.DataGridView1.Rows.Add(SplitLine)
Loop
End Using
Else
MsgBox("File Does Not Exist")
End If

Related

VB.net how to disable column header download

Problem : I'm loading a csv file to dgv. There is a predefined column name that i set by UI design. Whenever i download this CSV file after loading into the dgv, it download the header repeatedly. Below is 2 photos.
Before download and After Clicking download 2times
Here is my download button code
Private Sub btnDownload_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDownload.Click
Dim oldFile As System.IO.FileInfo = New IO.FileInfo(filePath)
oldFile.Delete()
Dim headers = (From header As DataGridViewColumn In gridData.Columns.Cast(Of DataGridViewColumn)() _
Select header.HeaderText).ToArray
Dim rows = From row As DataGridViewRow In gridData.Rows.Cast(Of DataGridViewRow)() _
Where Not row.IsNewRow _
Select Array.ConvertAll(row.Cells.Cast(Of DataGridViewCell).ToArray, Function(c) If(c.Value IsNot Nothing, c.Value.ToString, ""))
Using sw As New IO.StreamWriter(filePath)
sw.WriteLine(String.Join(",", headers))
For Each r In rows
sw.WriteLine(String.Join(",", r))
Next
End Using
Process.Start(filePath)
End Sub
How can i stop this repeated header downloading?
Here is the upload csv file code:
Private Sub ReadCSV()
gridData.Rows.Clear()
Dim TextLine As String = ""
Dim SplitLine() As String
If System.IO.File.Exists(filePath) = True Then
Using objReader As New System.IO.StreamReader(filePath, Encoding.ASCII)
Do While objReader.Peek() <> -1
TextLine = objReader.ReadLine()
SplitLine = Split(TextLine, ",")
gridData.Rows.Add(SplitLine)
Loop
End Using
Else
MsgBox("File Does Not Exist")
End If
End Sub

Get percentage of files copied from a list

I have an app that copies files in a list to a new directory. I'm trying to get the progress bar to work but my formula results with a System.OverflowException: Arithmetic operation resulted in an over flow. I've looked at other examples using file copying but they are centered on using the source folder divided by destination folder. Mines a little bit different because I'm using files in a list.
Thank you for the help.
Code
Dim progress = fileCount * 100 / fileList.Count()
BackgroundWorker1.ReportProgress(progress)
Code for getting file Count
Dim FILE_NAME As String
FILE_NAME = txtFileName.Text
Dim fileNames = System.IO.File.ReadAllLines(FILE_NAME)
fCount = 0
For i = 0 To fileNames.Count() - 1
Dim fileName = fileNames(i)
sFileToFind = location & "\" & fileName & "*.*"
Dim paths = IO.Directory.GetFiles(location, fileName, IO.SearchOption.AllDirectories)
If Not paths.Any() Then
System.IO.File.AppendAllText(orphanedFiles, fileName & vbNewLine)
Else
For Each pathAndFileName As String In paths
If System.IO.File.Exists(pathAndFileName) = True Then
sRegLast = pathAndFileName.Substring(pathAndFileName.LastIndexOf("\") + 1)
Dim toFileLoc = System.IO.Path.Combine(createXMLFldr, sRegLast)
Dim moveToFolder = System.IO.Path.Combine(MoveLocation, "XML files", sRegLast)
'if toFileLoc = XML file exists move it into the XML files folder
If System.IO.File.Exists(toFileLoc) = False Then
System.IO.File.Copy(pathAndFileName, moveToFolder)
System.IO.File.AppendAllText(ListofFiles, sRegLast & vbNewLine)
fCount = fCount + 1
XMLFilename = (sRegLast) + vbCrLf
End If
End If
Next
End If
Dim srcCount = paths.Count()
If (paths.Count() = 0) Then
srcCount = 1
End If
Dim progress = CType(fCount * 100 / srcCount, Integer)
BackgroundWorker1.ReportProgress(progress)
Next
This for BackGroundWorker, I hope will this can resolve the trouble of the next call to update progress bar:
'This button1_click event to begin or stop async of backGrounedWorker
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
BackgroundWorker1.WorkerReportsProgress = True
BackgroundWorker1.WorkerSupportsCancellation = True
BackgroundWorker1.CancelAsync()
Try
BackgroundWorker1.RunWorkerAsync()
Catch ex As Exception
End Try
End Sub
'Here your backGroundProcess
Private Sub BackgroundWorker1_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
Dim FILE_NAME As String
FILE_NAME = txtFileName.Text 'can be changed
Dim fileNames = System.IO.File.ReadAllLines(FILE_NAME)
Dim Location As String = "C:\MyData\Folder1" 'can be changed
Dim moveToFolder As String = "C:\MyData\Folder2" 'can be changed
Dim fCount As Integer = 0
For Each fileName In fileNames
Dim paths = IO.Directory.GetFiles(Location, fileName,
IO.SearchOption.AllDirectories)
If paths.Count > 0 Then
Try
System.IO.File.Copy(paths(0), moveToFolder & "\" & fileName, True)
Catch ex As Exception
Debug.Print(ex.Message)
End Try
End If
For a = 1 To 100
Debug.Print(a.ToString)
Next
'If any request pending process will be stop (when Button1_click happen while process running (BackGroundWorker in Action))
If BackgroundWorker1.CancellationPending = True Then Exit For
fCount += 1
Dim Progress As Integer = Convert.ToInt32(fCount * 100 / fileNames.Count)
BackgroundWorker1.ReportProgress(progress)
Next
End Sub
'This will show you the progress in your progress bar
Private Sub bw1_ProgressChanged(sender As Object, e As System.ComponentModel.ProgressChangedEventArgs) Handles BackgroundWorker1.ProgressChanged
Me.ProgressBar1.Value = e.ProgressPercentage
End Sub
'Your Process Have Been Complete Here
Private Sub BackgroundWorker1_RunWorkerCompleted(sender As Object, e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted
MessageBox.Show("Finish")
End Sub
This last modification from me:
ListBox1.Items.Clear()
Dim FILE_NAME As String
FILE_NAME = "c:\YourFolder\YourFile.txt" 'can be changed
Dim fileNames = System.IO.File.ReadAllLines(FILE_NAME)
For Each MyFile In fileNames
ListBox1.Items.Add(MyFile)
Next
Dim Location As String = "C:\YourFolder1" 'can be changed
Dim moveToFolder As String = "C:\YourFolder2" 'can be changed
Dim fCount As Integer = 0
For Each fileName In fileNames
Dim paths = IO.Directory.GetFiles(Location, fileName,
IO.SearchOption.AllDirectories)
If paths.Count > 0 Then
Try
System.IO.File.Copy(paths(0), fileName)
Catch ex As Exception
End Try
End If
fCount += 1
Dim progress As Integer = Convert.ToInt32(fCount * 100 / fileNames.Count)
Next

Unable to cancel application

I have an application that copies files into different directories. As the application is running if I click the BtnExit_Click button nothing happens. I'm only able to exit out of the app after it has run through all the files to copy.
This is my code
Private Sub BtnExit_Click(sender As Object, e As EventArgs) Handles btnExit.Click
BackgroundWorker1.CancelAsync()
Me.Close()
End Sub
Background Worker:
Private Sub BackgroundWorker1_ProgressChanged(sender As Object, e As System.ComponentModel.ProgressChangedEventArgs) Handles BackgroundWorker1.ProgressChanged
Me.txtImgCount.Text = iCount
Me.txtImgCount.Update()
Me.fileCount.Text = fCount
Me.fileCount.Update()
Me.txtTotal.Update()
Me.Label8.Text = statusText
Me.Label8.Update()
Application.DoEvents()
Try
Me.RichTextBox1.Text &= (fileFilename)
Application.DoEvents()
Catch ei As DivideByZeroException
Debug.WriteLine("Exception caught: {0}", ei)
Finally
End Try
Try
Me.RichTextBox1.Text &= (imgFilename)
Application.DoEvents()
Catch ea As DivideByZeroException
Debug.WriteLine("Exception caught: {0}", ea)
Finally
End Try
End Sub
Private Sub BackgroundWorker1_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
RunCopyFiles()
End Sub
Private Sub RunCopyFiles()
BackgroundWorker1.WorkerReportsProgress = True
Dim sFileToFind As String
Dim location As String
'Dim File As String
statusText = "Initiating"
status = "Initiating..."
'Directory Files are located in
location = txtFolderPath.Text
'Directory ICN files are located in
imgLocation = txtSearchICN.Text
'Directory files are to copied into
MoveLocation = CopyToPath
createImgFldr = MoveLocation & "\Figures"
createReportFldr = MoveLocation & "\Reports"
createXMLFldr = MoveLocation & "\XML files"
'Create Figures Folder
If Not IO.Directory.Exists(createImgFldr) Then
IO.Directory.CreateDirectory(createImgFldr)
' MsgBox("folder created" & createFolder)
End If
'Create Reports folder
If Not IO.Directory.Exists(createReportFldr) Then
IO.Directory.CreateDirectory(createReportFldr)
'MsgBox("folder created" & createReportFldr)
End If
'Create XML folder
If Not IO.Directory.Exists(createXMLFldr) Then
IO.Directory.CreateDirectory(createXMLFldr)
' MsgBox("folder created" & createFolder)
End If
'Text file with list of file names
Dim filesToCopy = txtFileName.Text
orphanedFiles = MoveLocation & "\Reports\OrphanedFilesItems.txt"
' Create or overwrite the file.
System.IO.File.Create(orphanedFiles).Dispose()
ListofGraphics = MoveLocation & "\Reports\ListOfGraphics.txt"
' Create or overwrite the file.
System.IO.File.Create(ListofGraphics).Dispose()
Dim removDupBuildLog = MoveLocation & "\Reports\RemvoeDup.txt"
Dim ListLog = MoveLocation & "\Reports\ListOfGraphics.txt"
ListofFiles = MoveLocation & "\Reports\ListOfFiles.txt"
' Create or overwrite the file.
System.IO.File.Create(ListofFiles).Dispose()
MissingFiles = MoveLocation & "\Reports\MissingGraphicList.txt"
' Create or overwrite the file.
System.IO.File.Create(MissingFiles).Dispose()
Dim FILE_NAME As String
FILE_NAME = txtFileName.Text
Dim fileNames = System.IO.File.ReadAllLines(FILE_NAME)
status = "Copying SGML\XML Files"
statusText = "Copying SGML\XML Files..."
fCount = 0
For i = 0 To fileNames.Count() - 1
Dim fileName = fileNames(i)
sFileToFind = location & "\" & fileName & "*.*"
Dim paths = IO.Directory.GetFiles(location, fileName, IO.SearchOption.AllDirectories)
If Not paths.Any() Then
System.IO.File.AppendAllText(orphanedFiles, fileName & vbNewLine)
Else
For Each pathAndFileName As String In paths
If System.IO.File.Exists(pathAndFileName) = True Then
Dim sRegLast = pathAndFileName.Substring(pathAndFileName.LastIndexOf("\") + 1)
Dim toFileLoc = System.IO.Path.Combine(createXMLFldr, sRegLast)
Dim moveToFolder = System.IO.Path.Combine(MoveLocation, "XML files", sRegLast)
'if toFileLoc = XML file exists move it into the XML files folder
If System.IO.File.Exists(toFileLoc) = False Then
System.IO.File.Copy(pathAndFileName, moveToFolder)
System.IO.File.AppendAllText(ListofFiles, sRegLast & vbNewLine)
Application.DoEvents()
fileFilename = (fileName) + vbCrLf
fCount = fCount + 1
'fileCount.Text = fCount
End If
End If
Next
End If
BackgroundWorker1.ReportProgress(100 * (i + 1) / fileNames.Count)
Next
CreateGraphicsFunction()
GetImages()
Application.UseWaitCursor = False
Application.DoEvents()
End Sub
If you look at the code example in the documentation for the BackgroundWorker Class you will see that it checks the worker.CancellationPending property every time through the loop.
So you'll need a couple of changes:
Private Sub BackgroundWorker1_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
Dim worker As BackgroundWorker = CType(sender, BackgroundWorker)
RunCopyFiles(worker, e)
End Sub
Private Sub RunCopyFiles(worker As BackgroundWorker, e As DoWorkEventArgs)
... other code here
For Each pathAndFileName As String In paths
... other code here
If worker.CancellationPending Then
e.Cancel = True
Exit Sub
End If
Next
Maybe put another check just after the ReportProgress(...) too.
Also, you will need to set backgroundWorker1.WorkerSupportsCancellation = True.
The Application.UseWaitCursor = False should not be in the worker - put it in the code that calls backgroundWorker1.RunWorkerAsync().
As LarsTech wrote in a comment, you should remove all calls to Application.DoEvents(): problems with it are listed in Use of Application.DoEvents().
Finally, make sure that you are using Option Strict On.

How to import .csv file to my datagridview in vb.net?

My used code is:
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
Dim fName As String = ""
OpenFileDialog1.InitialDirectory = "c:\desktop"
OpenFileDialog1.Filter = "CSV files (*.csv)|*.CSV"
OpenFileDialog1.FilterIndex = 2
OpenFileDialog1.RestoreDirectory = True
If (OpenFileDialog1.ShowDialog() = Windows.Forms.DialogResult.OK) Then
fName = OpenFileDialog1.FileName
End If
txtpathfile.Text = fName
Dim TextLine As String = ""
Dim SplitLine() As String
If System.IO.File.Exists(fName) = True Then
Dim objReader As New System.IO.StreamReader(fName)
Do While objReader.Peek() <> -1
TextLine = objReader.ReadLine()
SplitLine = Split(TextLine, ",")
Me.DataGridView2.Rows.Add(SplitLine)
Loop
Else
MsgBox("File Does Not Exist")
End If
End Sub
My output looks wrongly encoded:
What's wrong with my code? Please help me. Thank you for consideration.
I arrived here from google. Just in case someone sarching for a quick code to copy:
Private Sub ReadCSV()
Dim fName As String = "C:\myfile.csv"
Dim TextLine As String = ""
Dim SplitLine() As String
If System.IO.File.Exists(fName) = True Then
Using objReader As New System.IO.StreamReader(fName, Encoding.ASCII)
Do While objReader.Peek() <> -1
TextLine = objReader.ReadLine()
SplitLine = Split(TextLine, ";")
Me.DataGridView1.Rows.Add(SplitLine)
Loop
End Using
Else
MsgBox("File Does Not Exist")
End If
End Sub
For anyone that has been looking for other solution, this works and let me add, delete and update the same datagrid without any problem
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Using ofd As OpenFileDialog = New OpenFileDialog()
If ofd.ShowDialog() = DialogResult.OK Then
file_path.Text = ofd.FileName
Dim lines As List(Of String) = File.ReadAllLines(ofd.FileName).ToList()
Dim list As List(Of User) = New List(Of User)
fill_Columns(lines)
For i As Integer = 1 To lines.Count - 1
Dim data As String() = lines(i).Split(",")
addElements(
data(0),
data(1),
data(2),
data(3),
data(4)
) 'All this elements has to match with the -fill_Columns- elements
Next
End If
End Using
End Sub
Use it on the button where you want to click it... Also add this
Private Sub fill_Columns(lines As List(Of String))
Dim columns() As String = lines(0).Split(",")
For Each item In columns
Dim col As New DataGridViewTextBoxColumn
col.HeaderText = item
col.Name = item
col.DataPropertyName = item
DataGridView1.Columns.Add(col)
Next
End Sub
Private Sub addElements(Code As String, Name As String, Birth As DateTime, Email As String, Address As String)
DataGridView1.Rows.Add(
Code,
Name,
Birth.ToString,
Email,
Address
) 'You add or delete as you need
End Sub
This is really work!
Dim fName As String = ""
OpenFileDialog1.InitialDirectory = "c:\desktop"
OpenFileDialog1.Filter = "CSV files(*.csv)|*.csv"
OpenFileDialog1.FilterIndex = 2
OpenFileDialog1.RestoreDirectory = True
If (OpenFileDialog1.ShowDialog() = Windows.Forms.DialogResult.OK) Then
fName = OpenFileDialog1.FileName
End If
txtpathfile.Text = fName
Dim TextLine As String = ""
Dim SplitLine() As String
If System.IO.File.Exists(fName) = True Then
Dim objReader As New System.IO.StreamReader(txtpathfile.Text, Encoding.ASCII)
Do While objReader.Peek() <> -1
TextLine = objReader.ReadLine()
SplitLine = Split(TextLine, ";")
Me.DataGridView1.Rows.Add(SplitLine)
Loop
Else
MsgBox("File Does Not Exist")
End If

how to filter a datagridview when a database is not being used

I am able get the contents of a csv file to read into DataGridView1, but I am having trouble filtering the data from textbox2. I tried different things I have found online, but nothing has worked so far. this is what i have:
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Dim fName As String = ""
OpenFileDialog1.InitialDirectory = "C:\"
OpenFileDialog1.Filter = "CSV Files (*.csv)|*.csv"
OpenFileDialog1.FilterIndex = 2
OpenFileDialog1.RestoreDirectory = True
If (OpenFileDialog1.ShowDialog() = Windows.Forms.DialogResult.OK) Then
fName = OpenFileDialog1.FileName
End If
Me.TextBox1.Text = fName
GetData(fName, DataGridView1, True)
End Sub
Private Sub GetData(ByVal Path As String, ByRef DG As DataGridView, Optional ByVal NoHeader As Boolean = False)
Dim Fields() As String
Dim Start As Integer = 1
If NoHeader Then Start = 0
If Not File.Exists(Path) Then
Return
End If
Dim Lines() As String = File.ReadAllLines(Path)
Lines(0) = Lines(0).Replace(Chr(34), "")
Fields = Lines(0).Split(",")
If NoHeader Then
For I = 1 To Fields.Count - 1
Fields(I) = Str(I)
Next
End If
For Each Header As String In Fields
DG.Columns.Add(Header, Header)
Next
For I = Start To Lines.Count - 1
Lines(I) = Lines(I).Replace(Chr(34), "")
Fields = Lines(I).Split(",")
DG.Rows.Add(Fields)
Next
End Sub
I just want to be able to filter say column 5 (no column headers in csv file) by typing something in textbox2. Any help would be greatly appreciated. Thank you
Don't add the values to a DGV, but instead use a DataTable then just make a query on that. Example considers you have a combobox for some filter choices - they are other ways to get this to depending on your needs. This method requires you to have headers though.
Private dt As New DataTable
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Dim fName As String = ""
OpenFileDialog1.InitialDirectory = "C:\"
OpenFileDialog1.Filter = "CSV Files (*.csv)|*.csv"
OpenFileDialog1.FilterIndex = 2
OpenFileDialog1.RestoreDirectory = True
If (OpenFileDialog1.ShowDialog() = Windows.Forms.DialogResult.OK) Then
fName = OpenFileDialog1.FileName
End If
Me.TextBox1.Text = fName
LoadData(fName)
FilterData(combobox1.Text, "some column name")
End Sub
Private Sub LoadData(ByVal Path As String)
Dim Fields() As String
Dim Start As Integer = 1
If NoHeader Then Start = 0
If Not File.Exists(Path) Then
Return
End If
Dim Lines() As String = File.ReadAllLines(Path)
Lines(0) = Lines(0).Replace(Chr(34), "")
Fields = Lines(0).Split(",")
For I = 1 To Fields.Count - 1
Fields(I) = Str(I)
Next
For Each Header As String In Fields
dt.Columns.Add(Header, Header)
Next
For I = Start To Lines.Count - 1
Lines(I) = Lines(I).Replace(Chr(34), "")
Fields = Lines(I).Split(",")
dt.Rows.Add(Fields)
Next
End Sub
Private Sub FilterData(filter As String, columnName as string)
Dim query = From dr As DataRow In dt.Rows Where dr(columnName).ToString = filter
DGV.DataSource = query
End Sub