Random access file visual basic 2012 - vb.net

I am having trouble making my record number unique in visual basic 2012 the code i have so far is overwriting the file that was previously saved??
my module
Imports System.IO
Module AssModule
Structure employee
' Public Name As String
' Public ID As String
<VBFixedString(30)> Dim name As String ' vb fixed string
<VBFixedString(5)> Dim id As String ' vb fixed string
End Structure
Structure transaction
<VBFixedString(5)> Dim id As String ' vb fixed string
Dim time As Date
<VBFixedString(3)> Dim type As String ' vb fixed string
End Structure
' Public fileSize As Integer = Len(index)
' Public Staff(100) As employee ' staff as new name for eployeee structure
Public myEmployee As employee
Public r As Integer = 5
Public fileNumber As Integer = FreeFile()
Public mySizerecordnumber As Integer = Len(myEmployee)
Public recordNumber As Integer
Public index As Byte
Public Sub setRecordNumber()
Dim n As Byte = 0
FileOpen(fileNumber, "binData.dat", OpenMode.Random, OpenAccess.Read)
While Not EOF(fileNumber)
n = n + 1
FileGet(fileNumber, myEmployee, n)
End While
recordNumber = n
FileClose(fileNumber)
End Sub
End Module
add employee button
Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
For n = 0 To 3
FileOpen(fileNumber, "binData.dat", OpenMode.Random, OpenAccess.Write, , mySizerecordnumber)
myEmployee.id = txtID.Text
myEmployee.name = txtName.Text
recordNumber = recordNumber + 1
FilePut(fileNumber, myEmployee, recordNumber)
FileClose(fileNumber)
Next
Me.Close()
End Sub

OK, let's break down your btnSave_Click function.
For 0 to 3, each time, you: open the file, read it, put the result in myEmployee, then put it back in the file and close.
What you want to do (I think) is to save the new employee at the end of your file
You should open your file, move to the end, and save your new record:
Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
setRecordNumber()
FileOpen(fileNumber, "binData.dat", OpenMode.Random, OpenAccess.Write, , mySizerecordnumber)
myEmployee.id = txtID.Text
myEmployee.name = txtName.Text
FilePut(fileNumber, myEmployee, recordNumber)
FileClose(fileNumber)
Me.Close()
End Sub

Related

find in a text file all rows with a specific value and display them in the datagridview

Good day!
There is a .csv text file in the following format:
Fred Smith
f.smith
engineer
21.12.2021
Ben Taylor
b.taylor
programmer
23.12.2021
Bill Davis
b.davis
programmer
19.12.2021
Steve Harris
s.harris
engineer
23.12.2021
Tom Walker
t.walker
engineer
23.12.2021
with the following code I display data from a text file into a DataGridView:
Dim list() As String = IO.File.ReadAllLines("D:\UserList.csv", System.Text.Encoding.Default)
For i = 0 To UBound(list)
DataGridView1.Rows.Add()
Dim data() As String = Split(list(i), "|")
For j = 0 To UBound(data) - 1
DataGridView1.Item(j, i).Value = data(j)
Next
Next
Tell me how you can display in the datagridview from a text file only those employees where a certain date is indicated in the line of the text file?
For instance:
Specified the date - 23.12.2021
In the DataGridView I want the following result to be displayed:
Ben Taylor
b.taylor
programmer
23.12.2021
Steve Harris
s.harris
engineer
23.12.2021
Tom Walker
t.walker
engineer
23.12.2021
Tell me how you can make such a selection before displaying data from a text file in the DataGridView?
However, do not delete these lines in the text file.
For j = 0 To UBound(data)-1
loop run before Date of joining column so that data not add to grid so i removed -1.
Actual problem for the new row should specify the row and column number as below code.
Dim list() As String = IO.File.ReadAllLines("D:\UserList.csv", System.Text.Encoding.Default)
For i = 0 To UBound(list)
DataGridView1.Rows.Add()
Dim data() As String = Split(list(i), "|")
For j = 0 To UBound(data)
'DataGridView1.Item(j, i).Value = data(j)
DataGridView1.Rows(i).Cells(j).Value = data(j)
Next
Next
There are several ways available. If you put the data into something which implements the IBindingListView interface such as a DataTable then you could use the Filter property. Documentation for that: BindingSource.Filter Property
Or, as I show here, you can use a List and use LINQ to create the filter, like this:
Imports System.IO
Public Class Form1
Dim userData As List(Of User) = Nothing
Dim inputDateFormat As String = "dd.MM.yyyy"
Dim displayDateFormat As String = "dd.MM.yyyy"
Public Class User
Property Name As String
Property Email As String
Property Title As String
Property MagicDate As DateTime
Sub New(name As String, email As String, title As String, magicDate As DateTime)
Me.Name = name
Me.Email = email
Me.Title = title
Me.MagicDate = magicDate
End Sub
End Class
Sub LoadData(src As String)
userData = New List(Of User)
For Each a In File.ReadLines(src)
Dim parts = a.Split("|"c)
If parts.Count = 4 Then
Dim md = DateTime.ParseExact(parts(3), inputDateFormat, Nothing)
Dim u = New User(parts(0), parts(1), parts(2), md)
userData.Add(u)
End If
Next
End Sub
Sub ShowData()
' show all the data
ShowData(Nothing)
End Sub
Sub ShowData(selectedDate? As DateTime)
If userData Is Nothing Then
Exit Sub
End If
Dim bs As New BindingSource
If selectedDate.HasValue Then
' select only the data with the desired date
bs.DataSource = userData.Where(Function(u) u.MagicDate = selectedDate.Value)
Else
' show all the data
bs.DataSource = userData
End If
DataGridView1.DataSource = bs
DataGridView1.Columns("MagicDate").DefaultCellStyle.Format = displayDateFormat
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
LoadData("C:\temp\UserList.csv")
ShowData(New Date(2021, 12, 23))
End Sub
End Class
To get:
Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
Dim pattern As String = "23.12.2021"
Dim Path As String = "D:\UserList.csv"
Dim _row As String
Dim separator As Char = "|"
For Each _row In File.ReadAllLines(Path, Encoding.Default)
If _row.Contains(pattern) Then
DataGridView1.Rows.Add(_row.Split(separator))
End If
Next _row
End Sub
Why not do something like:
Dim list() As String = IO.File.ReadAllLines("D:\UserList.csv", System.Text.Encoding.Default)
Dim ub as Integer
For i = 0 To UBound(list)
Dim data() As String = Split(list(i), "|")
ub = UBound(data)
If data(ub) = "23.12.2021" Then
DataGridView1.Rows.Add()
For j = 0 To ub - 1
DataGridView1.Item(j, i).Value = data(j)
Next
End If
Next
Using the "User" class that Andrew Morton created:
Dim fileName = "C:\Bin\myFile.csv"
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim filterDate = Date.Parse("23.12.2021")
SetDataSource(filterDate)
End Sub
Private Sub SetDataSource(dateStamp As Date)
Dim data = File.ReadAllLines(fileName).Skip(1).
Select(Function(line) line.Split(",")).
Select(Function(x) New User(x)).
Where(Function(x) x.MagicDate = dateStamp)
DataGridView1.DataSource = data.ToList()
End Sub
Public Class User
Public Sub New(x() As String)
Name = x.ElementAt(0)
Email = x.ElementAt(1)
Title = x.ElementAt(2)
MagicDate = x.ElementAt(3)
End Sub
Property Name As String
Property Email As String
Property Title As String
Property MagicDate As DateTime
End Class
I added the Skip(1) in the LINQ so it ignores the header row. This can be removed if no header is present.

i am trying to read a text file in visual basics but i am not able to store the details in the array it gives errors

Dim EmpId(100) As String
Dim Lastname(100) As String
Dim firstname(100) As String
Dim hrs(100) As Integer
Dim min(100) As Integer
Dim counter As Integer
Dim i As Integer
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
'declare variables
Dim result As DialogResult 'what did the user choose in the open dialog (open or cancel)
Dim strFileName As String 'store file path of the selected file
Dim strRecord As String
Dim sreStreamReader As IO.StreamReader
Dim strFieldValues(100) As String 'to store extracted field values.
Try
result = filebrowser.ShowDialog
If result = Windows.Forms.DialogResult.OK Then
strFileName = filebrowser.FileName
'create a StreamReader object by opening the file for input
sreStreamReader = IO.File.OpenText(strFileName)
counter = 0
i = 0
Do While sreStreamReader.Peek() <> -1
strRecord = sreStreamReader.ReadLine()
strFieldValues = strRecord.Split(",")
EmpId(counter) = strFieldValues(i) & firstname(counter) = strFieldValues(i) & Lastname(counter) = strFieldValues(i) _
& hrs(counter) = strFieldValues(i) & min(counter) = strFieldValues(i)
counter = counter + 1
i = i + 1
Loop
Dim j As Integer
For j = 0 To j < counter Step +1
Label1.Text = EmpId(j) & firstname(j) & Lastname(j) & hrs(j) & min(j)
Next
sreStreamReader.Close()
End If
Catch exFile As IO.FileNotFoundException
'processed when the file cannot be found
MessageBox.Show("Cannot locate the file.", _
"FileopenDialog", MessageBoxButtons.OK, _
MessageBoxIcon.Information)
' Catch ex As Exception
'handles any other errors
' MessageBox.Show(ex.Message, "FileopenDialog", _
' MessageBoxButtons.OK, MessageBoxIcon.Information)
End Try
I am assuming that your text file would look like this if opened in notepad.
1,Smith,Mary,7,45
2,Jones,Bill, 8,15
3,Mathew,Mark,6, 20
4,Luke,John,9,30
Notice there are no spaces. If there are spaces you may have to use .Trim on the strings.
I have a class called Employee. In the class there is a custom constructor (the Sub New) which sets all the appropriate properties. The values will come from the text file as you will see in a minute.
Then in the buttton click event a list of the type Employee is created.
Dim EmpList As New List(Of Employee)
It can hold objects of the type Employee. I use a `List(0f T) instead of an array because I don't have to know ahead of time how many lines are in the file.
The .ReadAllLines method of the File object returns an array containing each line in the file as an element of the array. Loop through the lines array calling .Split on each line which returns an array presumably containing each of the fields you are interested in. Each element is sent to the constructor of Employee and the resulting new Employee is added to the list. If there are extraneous spaces in the file this is where you may need to call .Trim to get rid of them
Finally, I have added a DataGridView to the form at design time. Set the .DataSource property to the list of employees and your data is displayed in the grid with headers.
Public Class Employee
Public Property ID As String
Public Property LasName As String
Public Property FirstName As String
Public Property Hours As Integer
Public Property Minutes As Integer
Public Sub New(iden As String, lname As String, fname As String, hr As Integer, mn As Integer)
ID = iden
LasName = lname
FirstName = fname
Hours = hr
Minutes = mn
End Sub
End Class
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim EmpList As New List(Of Employee)
Try
Dim result = OpenFileDialog1.ShowDialog
If Not result = Windows.Forms.DialogResult.OK Then
MessageBox.Show("No file selected")
End If
Dim strFileName = OpenFileDialog1.FileName
Dim lines = IO.File.ReadAllLines(strFileName)
For Each line In lines
Dim strFieldValues = line.Split(","c)
EmpList.Add(New Employee(strFieldValues(0), strFieldValues(1), strFieldValues(2), CInt(strFieldValues(3)), CInt(strFieldValues(4))))
Next
DataGridView1.DataSource = EmpList
Catch exFile As IO.FileNotFoundException
MessageBox.Show("Cannot locate the file.", "FileopenDialog", MessageBoxButtons.OK, MessageBoxIcon.Information)
End Try
End Sub

Search delimited textfile in 2D array

I have delimited a text file and put it into a 2D array. Then, I have tried to find out if the array contains the product ID (entered in a textbox). However, the code I have used to try to search the array and show the name does not work.
The textfile says:
1, Frances
2, Emma
Here is my code:
Public Class Form1
Dim filename As String
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
filename = "names.txt"
End Sub
Private Sub btnsearch_Click(sender As Object, e As EventArgs) Handles btnsearch.Click
filename = "names.txt"
FileOpen(1, filename, OpenMode.Input,,,)
Dim lines() As String = IO.File.ReadAllLines("names.txt")
Dim values(lines.Length - 1, 1) As String
For i As Integer = 0 To lines.Length - 1
Dim parts() As String = lines(i).Split(","c)
values(i, 0) = parts(0)
values(i, 1) = parts(1)
Next
Dim ID As String
ID = txtidsearch.Text
Dim line As String
Do While Not EOF(1)
line = LineInput(1)
If values().Contains(ID) Then
lblid.Text = line
Application.DoEvents()
GoTo line1
ElseIf EOF(1) = True
MsgBox("Not Found")
End If
Loop
line1:
FileClose(1)
End Sub
End Class
Thanks in advance
What I would do is create a class to hold your people. It would make it easier in the long run.
First create a Person class:
Imports System.Collections.ObjectModel
Public Class Person
Public Key As String
Public Sub New(ByVal id As Integer,
ByVal name As String,
ByVal form as String)
_id = id
_name = name
_form = form
End Sub
Private _id As Integer
Public ReadOnly Property Id() As Integer
Get
Return _id
End Get
End Property
Private _name As String
Public ReadOnly Property Name() As String
Get
Return _name
End Get
End Property
Private _form As String
Public ReadOnly Property Form() As String
Get
Return _form
End Get
End Property
End Class
Now create a People class which will be a collection to hold each Person:
Public Class People
Inherits KeyedCollection(Of String, Person)
Protected Overrides Function GetKeyForItem(ByVal item As Person) As String
Return item.Key
End Function
End Class
I would then change this bit of code:
Dim values(lines.Length - 1, 1) As String
For i As Integer = 0 To lines.Length - 1
Dim parts() As String = lines(i).Split(","c)
values(i, 0) = parts(0)
values(i, 1) = parts(1)
Next
To this:
Dim myPeople As New People
For i As Integer = 0 To lines.Length - 1
Dim parts() As String = lines(i).Split(","c)
myPeople.Add(New Person(parts(0), parts(1), parts(2)))
Next
Note that I am adding a new Person class to the People collection class.
And I would replace this code:
Dim line As String
Do While Not EOF(1)
line = LineInput(1)
If values().Contains(ID) Then
lblid.Text = line
Application.DoEvents()
GoTo line1
ElseIf EOF(1) = True
MsgBox("Not Found")
End If
Loop
line1:
With this:
Dim filteredLines = From people In myPeople
Where people.Id = ID
Select people
If filteredLines IsNot Nothing AndAlso filteredLines.Count = 1 Then
Label1.Text = filteredLines(0).Name
End If
This last bit of code is LINQ:
General-purpose query facilities added to the .NET Framework apply to all sources of information, not just relational or XML data. This facility is called .NET Language-Integrated Query (LINQ).
Using LINQ we can query the People collection class like we would a table on a database using similar syntax. Here I am selecting all of the People where the ID matches. I then check to ensure that filteredLines actually has a Person before assigning the value.

Multiple Search Criteria (VB.NET)

So my problem is:
I have a List of a custom Type {Id as Integer, Tag() as String},
and i want to perform a multiple-criteria search on it; eg:
SearchTags={"Document","HelloWorld"}
Results of the Search will be placed a ListBox (ListBox1) in this format:
resultItem.id & " - " & resultItem.tags
I already tried everything i could find on forums, but it didn't work for me (It was for db's or for string datatypes)
Now, i really need your help. Thanks in advance.
For Each MEntry As EntryType In MainList
For Each Entry In MEntry.getTags
For Each item As String In Split(TextBox1.Text, " ")
If Entry.Contains(item) Then
If TestIfItemExistsInListBox2(item) = False Then
ListBox1.Items.Add(item & " - " & Entry.getId)
End If
End If
Next
Next
Next
Example Custom Array:
(24,{"snippet","vb"})
(32,{"console","cpp","helloworld"})
and so on...
I searched for ("Snippet vb test"):
snippet vb helloWorld - 2
snippet vb tcpchatEx - 16
cs something
test
So, i'll get everything that contains one of my search phrases.
I expected following:
snippet vb tcp test
snippet vb dll test
snippet vb test metroui
So, i want to get everything that contains all my search phrases.
My entire, code-likely class
Imports Newtonsoft.Json
Public Class Form2
Private Sub Form2_Load(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
Dim MainList As New List(Of EntryType)
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
MainList.Clear()
Dim thr As New Threading.Thread(AddressOf thr1)
thr.SetApartmentState(Threading.ApartmentState.MTA)
thr.Start()
End Sub
Delegate Sub SetTextCallback([text] As String)
Private Sub SetTitle(ByVal [text] As String) ' source <> mine
If Me.TextBox1.InvokeRequired Then
Dim d As New SetTextCallback(AddressOf SetTitle)
Me.Invoke(d, New Object() {[text]})
Else
Me.Text = [text]
End If
End Sub
Sub thr1()
Dim linez As Integer = 1
Dim linex As Integer = 1
For Each line As String In System.IO.File.ReadAllLines("index.db")
linez += 1
Next
For Each line As String In System.IO.File.ReadAllLines("index.db")
Try
Application.DoEvents()
Dim a As saLoginResponse = JsonConvert.DeserializeObject(Of saLoginResponse)(line) ' source <> mine
Application.DoEvents()
MainList.Add(New EntryType(a.id, Split(a.tags, " ")))
linex += 1
SetTitle("Search (loading, " & linex & " of " & linez & ")")
Catch ex As Exception
End Try
Next
SetTitle("Search")
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim searchTags() As String = TextBox1.Text.Split(" ")
Dim query = MainList.Where(Function(et) et.Tags.Any(Function(tag) searchTags.Contains(tag))).ToList
For Each et In query
ListBox1.Items.Add(et.Id)
Next
End Sub
Private Sub Button4_Click(sender As Object, e As EventArgs) ' test
MsgBox(Mid(ListBox1.SelectedItem.ToString, 1, 6)) ' test
End Sub 'test, removeonrelease
End Class
Public Class EntryType
Public Property Id As Integer
Public Property Tags() As String
Public Sub New(ByVal _id As Integer, ByVal _tags() As String)
Me.Id = Id
Me.Tags = Tags
End Sub
Public Function GetTags() As String
'to tell the Listbox what to display
Return Tags
End Function
Public Function GetId() As Integer
'to tell the Listbox what to display
Return Id
End Function
End Class
I also edited your EntryType class; I added a constructor, removed toString and added GetTags and GetID.
Example "DB" im working with ("db" as "index.db" in exec dir):
{"tags":"vb.net lol test qwikscopeZ","id":123456}
{"tags":"vb.net lol test","id":12345}
{"tags":"vb.net lol","id":1234}
{"tags":"vb.net","id":123}
{"tags":"cpp","id":1}
{"tags":"cpp graphical","id":2}
{"tags":"cpp graphical fractals","id":3}
{"tags":"cpp graphical fractals m4th","id":500123}
Error:
Debugger:Exception Intercepted: _Lambda$__1, Form2.vb line 44
An exception was intercepted and the call stack unwound to the point before the call from user code where the exception occurred. "Unwind the call stack on unhandled exceptions" is selected in the debugger options.
Time: 13.11.2014 03:46:10
Thread:<No Name>[5856]
Here is a Lambda query. The Where filters on a predicate, since Tags is an Array you can use the Any function to perform a search based on another Array-SearchTags. You can store each class object in the Listbox since it stores Objects, you just need to tell it what to display(see below).
Public Class EntryType
Public Property Id As Integer
Public Property Tags() As As String
Public Overrides Function ToString() As String
'to tell the Listbox what to display
Return String.Format("{0} - {1}", Me.Id, String.Join(Me.Tags, " "))
End Function
End Class
Dim searchTags = textbox1.Text.Split(" "c)
Dim query = mainlist.Where(Function(et) et.Tags.Any(Function(tag) searchTags.Contains(tag))).ToList
For Each et In query
Listbox1.Items.Add(et)
Next

how to read from text file to textbox in visual basic 1 line every hit on button

I have files type .txt (Text File) and it's have multiple line and i have these pictures
i want to make program generate fake information
Mean: when some one hit generate button it's ready from text file and fill textbox in visual basic
every hit(press) on Generate Button make program generate new information from text files (.txt)
i tried a lot ways:
Code:
Dim fileReader As String
fileReader = My.Computer.FileSystem.ReadAllText("C:\test.txt")
Code:
Dim fileReader As String
fileReader = My.Computer.FileSystem.ReadAllText("C:\test.txt", _
System.Text.Encoding.UTF32)
and this
Code:
Dim oFile as System****.File
Dim oRead as System****.StreamReader
oRead = oFile.OpenText(“C:\test.txt”)
and this
Code:
Dim FILE_NAME As String = "C:\Users\user\Desktop\test.txt"
Dim objReader As New System.I--O.StreamReader(FILE_NAME)
TextBox1.Text = objReader.ReadToEnd
Code:
' Form Load :
Dim text As String = MsgBox("text you want to make the form remember it.")
Or new Sub :
Code:
Private Sub Text
text
Code:
' Button Click :
Text()
Code:
Dim path As String = "THE FILE PATH" 'The file path
Dim reader As New IO.StreamReader(path)
Dim lineIndex As Integer = 2 ' The index of the line that you want to read
For i As Integer = 0 To lineIndex - 1
reader.ReadLine()
Next
TextBox1.Text = reader.ReadLine
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
TextBox1.Text = ReadLineFromTxt("THE TXT FILE PATH", 0) '0 is the line index
End Sub
Public Shared Function ReadLineFromTxt(ByVal path As String, ByVal lineIndex As Integer) As String
Dim reader As New IO.StreamReader(path)
For I As Integer = 0 To lineIndex - 1
reader.ReadLine()
Next
Return reader.ReadLine()
End Function
End Class
These ways take from members in this fourm:
http://www.mpgh.net/forum/33-visual-basic-programming/693165-help-how-can-i-generate-text-txt-file-textbox-when-button-click-2.html
if are these ways working please tell me how to use it in best way
i have Visual studio 2012 and updated 1
With all due respect
Assuming you are reading from a file and displaying lines on the form, you can use these.
If you have a large file (> 10MB), then you can use this pattern... (syntax from memory, please excuse mistype)
Public Class YourFormNameHere
Private _CurrentLine as Integer = 0
Private Sub btnClicked(sender, e) 'or enter pressed - This is YOUR keypress event handler.
Using Dim sr as New StreamReader(filePath)
Dim _curIndex as Integer = 0
While (sr.EndOfFile == false)
Dim _line as String = sr.ReadLine()
If (_curIndex = _CurrentLine)
txtLineDisplay.Text = _line
Break
End If
curIndex += 1
End While
End Using
End Sub
End Class
If you have a smaller file, then use this pattern.
Public Class YourFormNameHere
Private _Lines as String()
Private _CurrentLine as Integer = 0
Private Sub formLoad(sender, e) 'one-time load event - This is YOUR form load event
_Lines = File.ReadAllLines(filePath)
End Sub
Private Sub btnClicked(sender, e) 'or enter pressed - This is YOUR keypress event handler.
txtLineDisplay.Text = _Lines(_CurrentLine)
_CurrentLine += 1
End Sub
End Class