how to filter a datagridview when a database is not being used - vb.net

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

Related

Remove duplicate characters from strings and find the shortest

I can not figure out how to select from the result or the shortest line itself or its number
(Yes, the solution is needed in such ancient operators)
Imports System.IO
Public Class Form1
Sub readputh(ByRef s As String)
s = ""
OpenFileDialog1.Filter = "Textfiles (*.txt)|*.txt"
OpenFileDialog1.ShowDialog()
Do While s = ""
s = OpenFileDialog1.FileName
Loop
End Sub
Sub writeputh(ByRef s As String)
s = ""
SaveFileDialog1.Filter = "Textfiles (*.txt)|*.txt"
SaveFileDialog1.ShowDialog()
Do While s = ""
s = SaveFileDialog1.FileName
Loop
End Sub
Sub ch(ByVal Str As String, ByRef Res As String)
Dim a As Char
Res = Mid(Str, 1, 1)
For i = 2 To Len(Str)
a = CChar(Mid(Str, i, 1))
If InStr(Res, a) = 0 Then
Res = Res + a
End If
Next
End Sub
Sub resh(ByVal filename1 As String, ByVal filename2 As String, ByRef lb1 As ListBox, ByRef lb2 As ListBox)
Dim rf As StreamReader
Dim wf As StreamWriter
Dim s1, s2, s3 As String
s2 = ""
s3 = ""
Try
rf = New StreamReader(filename1)
wf = New StreamWriter(filename2, True)
Do While Not rf.EndOfStream()
s1 = rf.ReadLine()
lb1.Items.Add(s1)
ch(s1, s2)
wf.WriteLine(s2)
lb2.Items.Add(s2)
Loop
wf.Close()
rf.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim filename1, filename2 As String
readputh(filename1)
writeputh(filename2)
resh(filename1, filename2, ListBox1, ListBox2)
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
End
End Sub
End Class
Input file:
youtubeyoutubeyotube
dogdogdogdog
geeksforgeeks
Output file:
youtbe
dog
geksfor
But I expect Output file of only "dog"
I just couldn't handle the old code. One based functions? No! You can translate it back it you want but output is now dog.
Private Function GetOpenPath() As String
OpenFileDialog1.Filter = "Textfiles (*.txt)|*.txt"
If OpenFileDialog1.ShowDialog() = Windows.Forms.DialogResult.OK Then
Return OpenFileDialog1.FileName
Else
Return Nothing
End If
End Function
Private Function GetSavePath() As String
SaveFileDialog1.Filter = "Textfiles (*.txt)|*.txt"
If SaveFileDialog1.ShowDialog() = Windows.Forms.DialogResult.OK Then
Return SaveFileDialog1.FileName
Else
Return Nothing
End If
End Function
Private Function ch(ByVal Str As String) As String
Dim a As Char
Dim Res = Str.Substring(0, 1)
For i = 1 To Str.Length - 1
a = CChar(Str.Substring(i, 1))
If Res.IndexOf(a) = -1 Then
Res &= a
End If
Next
Return Res
End Function
Sub resh(ByVal filename1 As String, ByVal filename2 As String)
Dim lines = File.ReadAllLines(filename1)
Dim NewLines As New List(Of String)
For Each line In lines
Try
ListBox1.Items.Add(line)
Dim s2 = ch(line)
NewLines.Add(s2)
ListBox2.Items.Add(s2)
Catch ex As Exception
MsgBox(ex.Message)
End Try
Next
Dim Shortest = NewLines.OrderByDescending(Function(s) s.Length).Last()
File.WriteAllText(filename2, Shortest)
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim OpenPath = GetOpenPath()
Dim SavePath = GetSavePath()
If String.IsNullOrEmpty(OpenPath) OrElse String.IsNullOrEmpty(SavePath) Then
MessageBox.Show("You must provide a file. Try again.")
Return
End If
resh(OpenPath, SavePath)
End Sub

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 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.

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

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