VB Read file and set combobox.text value with text file value - vb.net

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.

Related

Reading .txt files using StreamReader

I am having an issue, I have a program I'm working on and I have to be able to read multiple .txt files one after the other to update a string array called words(). The main problem is the first file I upload goes into the files()string array, when I run my drag and drop event the array is full and won't let me upload second. how do I reset the files()array after it has been uploaded successfully.
sample code:
Dim words(7) As String
Dim i As Integer = 0
Public Sub frmMain_DragDrop(sender As Object, e As DragEventArgs) Handles MyBase.DragDrop
Dim word As String = ""
Try
Dim files() As String = e.Data.GetData(DataFormats.FileDrop)
For Each path In files
MsgBox(path)
Dim sr As New StreamReader(path)
Do Until sr.Peek = -1
word = sr.ReadLine()
words(i) = word
frmDefaultkWh.lbDefaultkWh.Items.Add(cbAppliances.Items(i) + " = " + words(i))
i = i + 1
Loop
Next
GetPower()
Catch ex As Exception
'MessageBox.Show(ex.ToString())
End Try
End Sub
Private Sub frmMain_DragEnter(sender As Object, e As DragEventArgs) Handles MyBase.DragEnter
If e.Data.GetDataPresent(DataFormats.FileDrop) Then
e.Effect = DragDropEffects.Copy
End If
End Sub
I believe this is because you are not resetting i, which means that eventually i increments out of the range of your words() array which is only size 7, which by the way will also throw an error if one of those files has more than 7 lines.
For Each path In files
i = 0 'reset counter
MsgBox(path)
Dim sr As New StreamReader(path)
Do Until sr.Peek = -1
word = sr.ReadLine()
words(i) = word
frmDefaultkWh.lbDefaultkWh.Items.Add(cbAppliances.Items(i) + " = " + words(i))
i = i + 1
Loop
Next

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

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

How do I get the file name only, assign it to a variable and use later?

I have the following code:
Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
Dim myStream As Stream
Dim saveFileDialog1 As New SaveFileDialog()
Dim saveFileName As String = ""
saveFileDialog1.Filter = "txt files (*.txt)|*.txt"
saveFileDialog1.RestoreDirectory = True
If saveFileDialog1.ShowDialog() = DialogResult.OK Then
myStream = saveFileDialog1.OpenFile()
saveFileDialog1.FileName = saveFileName
Using sw As StreamWriter = New StreamWriter(myStream)
' Add some text to the file.
sw.WriteLine(DateTime.Now + " - " + saveFileName) ' Date and File title header
sw.WriteLine("-------------------")
' Arbitrary objects can also be written to the file.
sw.Write("The date is: ")
sw.WriteLine(DateTime.Now)
sw.Close()
End Using
If (myStream IsNot Nothing) Then
' Code to write the stream goes here.
myStream.Close()
End If
End If
End Sub
The variable is saveFileName, however when I use the saveFileDialog1.FileName as it, it is empty or provides the full path to the file, how do I only get the name? (such as test.txt)
Use Path.GetFileName
saveFileName = Path.GetFileName(saveFileDialog1.FileName)
DIM fileName = IO.Path.GetFileName(SavefileDialog.FileName)