How to import .csv file to my datagridview in vb.net? - 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

Related

Attachment from Datagridview VB.NET

Can someone tell me is it correct now , how to read files from Datagridview in attachment.
I need to fetch the items from the datagridview and add them in the email attachment.
How i can fetch them?
How can i manage it in function SendMail() to support it?
Public Sub SendMail()
Dim oEmail As MailItem = CType(New Application().CreateItem(OlItemType.olMailItem), MailItem)
oEmail.Recipients.Add("emailTo") 'Send TO
oEmail.CC = "CopyEmail" 'Send CC
oEmail.Recipients.ResolveAll()
oEmail.Subject = "Spam - Meow!"
oEmail.BodyFormat = OlBodyFormat.olFormatHTML
oEmail.Body = "Blah, blah, blah..."
oEmail.Importance = OlImportance.olImportanceNormal 'Request read email confirmation
oEmail.ReadReceiptRequested = True
**If DataGridView1.Rows.Count > 0 Then
For Each row As DataGridViewRow In DataGridView1.Rows
If row.Cells("Name").Tag IsNot Nothing Then
Dim MsgAttach As New Attachment(CStr(row.Cells("Name").Tag))
oEmail.Attachments.Add(MsgAttach)
End If
Next
End If**
oEmail.Recipients.ResolveAll()
oEmail.Save()
oEmail.Display(False) 'Show the email message and allow for editing before sending
oEmail.Send() 'You can automatically send the email without displaying it.
End Sub
Button Browse:
OpenFileDialog1.FileName = "Folder1"
OpenFileDialog1.DefaultExt = "*.*"
OpenFileDialog1.FilterIndex = 6
OpenFileDialog1.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop)
OpenFileDialog1.Multiselect = True
Dim saveDirectory As String = ".\Files\"
If OpenFileDialog1.ShowDialog() = DialogResult.OK Then
If Not Directory.Exists(saveDirectory) Then
Directory.CreateDirectory(saveDirectory)
End If
For Each item As String In OpenFileDialog1.FileNames
Dim fileName As String = Path.GetFileName(OpenFileDialog1.FileName)
Dim fileSavePath As String = Path.Combine(saveDirectory, fileName)
File.Copy(OpenFileDialog1.FileName, fileSavePath, True)
Next
End If
BindDataGrid()
Private Sub BindDataGrid()
Dim filePaths As String() = Directory.GetFiles(".\Files\")
Dim dt As DataTable = New DataTable()
dt.Columns.Add("Text")
dt.Columns.Add("Value")
For Each filePath As String In filePaths
dt.Rows.Add(IO.Path.GetFileName(filePath), filePath)
Next
dataGridView1.AllowUserToAddRows = False
dataGridView1.Columns.Clear()
Dim name As DataGridViewColumn = New DataGridViewTextBoxColumn With {
.Name = "Name",
.HeaderText = "File Name",
.DataPropertyName = "Text",
.Width = 100
}
DataGridView1.Columns.Insert(0, name)
Dim path As DataGridViewColumn = New DataGridViewTextBoxColumn With {
.Name = "Path",
.HeaderText = "File Path",
.DataPropertyName = "Value",
.Width = 100
}
DataGridView1.Columns.Insert(1, path)
DataGridView1.DataSource = dt
Dim buttonColumn As DataGridViewButtonColumn = New DataGridViewButtonColumn With {
.HeaderText = "",
.Width = 60,
.Name = "buttonColumn",
.Text = "Delete",
.UseColumnTextForButtonValue = True
}
DataGridView1.Columns.Insert(2, buttonColumn)
End Sub
Private Sub DataGridView1_CellContentClick(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView1.CellContentClick
If e.ColumnIndex = 2 Then
Dim row As DataGridViewRow = DataGridView1.Rows(e.RowIndex)
If MessageBox.Show(String.Format("Do you want to delete Name:{0}?", row.Cells("Name").Value), "Confirmation", MessageBoxButtons.YesNo) = DialogResult.Yes Then
File.Delete(row.Cells("Path").Value.ToString())
BindDataGrid()
End If
End If
End Sub
How can i get from datagridview the items to attach it to email?

How to change filepath when check a radiobutton? Visual basic

My problem here is that i have 3 radiobuttons for 3 different categories:
Huse Folii and Altele.
The idea is when i select a radiobutton,the filepath will change to Huse,Folii or Altele.
For example i tried to make _path :
Dim _path As String = IO.Path.Combine("C:\Descriere\Huse\")
then use the _path here:
Dim ioFile As New System.IO.StreamReader(_path + "a.txt")
but it didn't worked,for sure i do something wrong,but i can't find how or where to use that _path...
Here is the code:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
On Error Resume Next
TextBox1.Clear()
If RadioButton1.Checked = True Then
Dim _path As String = IO.Path.Combine("C:\Descriere\Huse\")
End If
If RadioButton2.Checked = True Then
Dim _path As String = IO.Path.Combine("C:\Descriere\Folii\")
End If
If RadioButton3.Checked = True Then
IO.Path.
Dim _path As String = IO.Path.Combine("C:\Descriere\Altele\")
End If
Dim ioFile As New System.IO.StreamReader(_path + "a.txt")
Dim lines As New List(Of String)
Dim rnd As New Random()
Dim line As Integer
While ioFile.Peek <> -1
lines.Add(ioFile.ReadLine())
End While
line = rnd.Next(lines.Count + 1)
TextBox1.AppendText(lines(line).Trim())
ioFile.Close()
ioFile.Dispose()
Dim ioFile2 As New System.IO.StreamReader(path:=+"core.txt")
Dim lines2 As New List(Of String)
Dim rnd2 As New Random()
Dim line2 As Integer
While ioFile2.Peek <> -1
lines2.Add(ioFile2.ReadLine())
End While
line2 = rnd2.Next(lines2.Count + 1)
TextBox1.AppendText(lines2(line2).Trim())
ioFile2.Close()
ioFile2.Dispose()
Dim ioFile3 As New System.IO.StreamReader(path:=+"x.txt")
Dim lines3 As New List(Of String)
Dim rnd3 As New Random()
Dim line3 As Integer
While ioFile3.Peek <> -1
lines3.Add(ioFile3.ReadLine())
End While
line3 = rnd3.Next(lines3.Count + 1)
TextBox1.AppendText(lines3(line3).Trim())
ioFile3.Close()
ioFile3.Dispose()
TextBox1.Text = Replace(TextBox1.Text, "BRAND", TextBox2.Text)
TextBox1.Text = Replace(TextBox1.Text, "MODEL", TextBox3.Text)
Dim count As Integer = 0
count = TextBox1.Text.Split(" ").Length - 1
Label5.Text = "Caractere:" & Len(TextBox1.Text)
End Sub
You are using IO.Path.Combine but you have nothing to Combine at the place of use in your code. You have to use IO.Path.Combine later in your code because this is a method to Combine part of a path and a filename e.g. set your _path first and combine in a second step. Please note this code is not tested for your needs, because your coding is not clear to me.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim directoryName As String = "D:\"
On Error Resume Next
TextBox1.Clear()
If RadioButton1.Checked = True Then
directoryName = "D:\Descriere\Huse"
End If
If RadioButton2.Checked = True Then
directoryName = "D:\Descriere\Folii"
End If
If RadioButton3.Checked = True Then
'//--- IO.Path.
directoryName = "D:\Descriere\Altele"
End If
Dim ioFile As New System.IO.StreamReader(System.IO.Path.Combine(directoryName, "a.txt"))
...
Dim ioFile2 As New System.IO.StreamReader(System.IO.Path.Combine(directoryName, "core.txt"))
...
Dim ioFile3 As New System.IO.StreamReader(System.IO.Path.Combine(directoryName, "x.txt"))
...
End Sub
Please use the debugger of your IDE because your code isn't clean e.g. a hanging aroung IO.Path.

VB Read file and set combobox.text value with text file value

I have a configuration file with some saved values:
COM Port=COM4
Baud Rate=
Bits=
Parity=
Stop bits=
Mode=
CRC Byte=
When I load my Form I would like to read the txt file and write the values to a Combo Box to initialize the form values.
This is the code I have so far:
Private Sub Form2_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim ConfigFile As String
Dim Path As String
Dim WriteText As String
Dim ConfigVal As String()
' MsgBox("Form Load")
Path = Application.StartupPath
'ConfigFile = Path + "\ComConfig.txt"
ConfigFile = "C:\Users\wlowe\Documents\ComConfig.txt"
' If' Not System.IO.File.Exists(ConfigFile) = False Then
' System.IO.File.Create(ConfigFile).Dispose()
'End If
' Load Configuration values
Dim objReader As New System.IO.StreamReader(ConfigFile, True)
WriteText = objReader.ReadLine()
COMCombo.Text = WriteText
'MsgBox(objReader.ReadLine().ToString)
ConfigVal = WriteText.Split("=")
MsgBox(ConfigVal(1))
COMCombo.Text = ConfigVal(1)
WriteText = objReader.ReadLine()
BaudRateCombo.Text = WriteText
BitsCombo.Text = objReader.ReadLine()
ParityCombo.Text = objReader.ReadLine()
StopBitsCombo.Text = objReader.ReadLine()
ModeCombo.Text = objReader.ReadLine()
CRCCombo.Text = objReader.ReadLine()
objReader.Close()
End Sub
But when the form is loaded, the values for each combo box are blank.
Any help would be appreciated.

VB2010 read a csv in datagrid, update in grid and save to same csv

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

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