How to search a text file in Visual basic - vb.net

So my teacher wants the class to search a file for an authors name and display all the info on that author in a text box like a mailing label.
Here is my code i added a picture below. I'm really lost as to getting the program to take the Authors string and search another file. I can display the Authors name prefectly but how do you search another file for that name and display the information on that line about the author?
Imports System.IO
Public Class Form1
' CSCI 6
' Alex Smutny
' Lab #3
'
' DATE: 3/1/2013
Dim SR As IO.StreamReader
' initial start spot for the record Count
Dim RecordCount As Integer = 0
Dim Author As String = File.ReadAllText("Authors.txt")
Private Sub btnQuit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles quitBtn.Click
' Properly Exits the application.
Me.Close()
End Sub
Private Sub btnClose_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles closeBtn.Click
readBtn.Text = "Read"
SR.Close()
' Changes the button statuses Locked or unlocked and sets default settings.
openBtn.Enabled = True
quitBtn.Enabled = True
readBtn.Enabled = False
closeBtn.Enabled = False
SearBtn.Enabled = False
RecordCount = 0
recordNum.Clear()
bookNum.Clear()
isbnNum.Clear()
bookTitle.Clear()
authorName.Clear()
bookPrice.Clear()
bookQuanity.Clear()
reorderPoint.Clear()
End Sub
Private Sub btnOpen_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles openBtn.Click
' Sets the file to read from and opens it.
SR = IO.File.OpenText("Books.Txt")
' Changes the status of the buttons again now that the File is open and ready to read.
openBtn.Enabled = False
quitBtn.Enabled = False
readBtn.Enabled = True
closeBtn.Enabled = True
SearBtn.Enabled = True
End Sub
Private Sub btnRead_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles readBtn.Click
'Changes the Read button to say next because it makes more since.
readBtn.Text = "Next"
' Setting all the variables.
Dim srIndex1 As Integer = 18
Dim srTitle As Integer
Dim srAuthor As Integer
Dim srPrice As Integer
Dim srDPrice As Double
Dim srData As String
Dim srLength As Integer
If SR.Peek() = -1 Then
MessageBox.Show("End of file")
Else
' Starts to read
srData = SR.ReadLine
' Increment counter by 1.
RecordCount = RecordCount + 1
' Determine the record length.
srLength = srData.Length
' gets the book number
bookNum.Text = srData.Substring(0, 3)
' ISBN number
isbnNum.Text = srData.Substring(4, 13)
' Book title
For srTitle = 1 To srLength Step 1
If srData.Substring(srIndex1 + srTitle, 1) = "," Then
bookTitle.Text = srData.Substring(srIndex1, srTitle)
srIndex1 = srIndex1 + srTitle + 1
srTitle = srLength + 1
End If
Next
' Book Author
For srAuthor = 1 To srLength Step 1
If srData.Substring(srIndex1 + srAuthor, 1) = "," Then
authorName.Text = srData.Substring(srIndex1, srAuthor)
srIndex1 = srIndex1 + srAuthor + 1
srAuthor = srLength + 1
Author = authorName.Text
End If
Next
' Book Price
For srPrice = 1 To srLength Step 1
If srData.Substring(srIndex1 + srPrice, 1) = "," Then
srDPrice = CDbl(srData.Substring(srIndex1, srPrice))
bookPrice.Text = srDPrice.ToString("C")
srIndex1 = srIndex1 + srPrice + 1
srPrice = srLength + 1
End If
Next
' Quanity
bookQuanity.Text = srData.Substring(srIndex1, 2)
srIndex1 = srIndex1 + 3
' Reorder Point
reorderPoint.Text = srData.Substring(srIndex1, 2)
End If
' record count
recordNum.Text = RecordCount
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
openBtn.Enabled = True
quitBtn.Enabled = True
readBtn.Enabled = False
closeBtn.Enabled = False
SearBtn.Enabled = False
End Sub
Private Sub SearBtn_Click(sender As System.Object, e As System.EventArgs) Handles SearBtn.Click
SR = IO.File.OpenText("Authors.Txt")
SR.Close()
readBtn.Text = "Restart"
RecordCount = 0
SR = IO.File.OpenText("Books.Txt")
End Sub
End Class
Authors File http://pastebin.com/t7C8ye9e
Books File http://pastebin.com/y6DNyUFd
So my goal is to just get the info for the current author and then get it from the other file and take out all trailing spaces and just display it as a mailing label.

There's a variety of good ways to do this. Let's, for now, assume that there's one author per line. If there is, you can get the entire string with My.Computer.FileSystem.ReadAllText() and use String.Split(Environment.NewLine) to split it on each new line. At any rate, you need to have some way to separate each author in the list. String.Split returns an array of String objects. You can then iterate through the array to determine if a term matches the search. Here's an example of a for loop.
'... search term given in param
'... after loading text file
Dim StrArr() As String
StrArr = AuthorsString.Split(Environment.NewLine)
Dim i as Integer
For i=0 to StrArr.Length - 1 Step 1
If StrArr(i).toLower = SearchTerm.toLower Then
'String is a match! Case insensitivity should make it a little easier for the user.
End If
Next
Let me know if you have any questions.

Related

Exporting CSV from ListView in VB.NET

i am having a bit of issue with exporting my data from a List-view in VB.NET i have included screenshots of what i am seeing basically i want to see only the Values in my csv file when i export it,
as you can see i am seeing what the List-box is showing, those values are coming from the List View Before Export. also i need the export to be in 1 column not rows as shown
any help would be great..
''''
Imports System.IO
Imports System.IO.StreamReader
Imports System.IO.StreamWriter
Imports System.Data.DataSet
Public Class Form1
Private Sub startcol_Click(sender As Object, e As EventArgs) Handles startcol.Click
Timer1.Enabled = True
End Sub
Private Sub stopcol_Click(sender As Object, e As EventArgs) Handles stopcol.Click
Timer1.Enabled = False
End Sub
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
Const MIN As Double = 5.0
Const MAX As Double = 400.0
Const DEC_PLACES As Integer = 2
Dim rnd As New Random
Dim list As Integer()
'Generate a random number X where MIN <= X < MAX and then round to DEC_PLACES decimal places.
Dim dbl As Double = Math.Round(rnd.NextDouble() * (MAX - MIN) + MIN, DEC_PLACES)
weight.Text = dbl
Dim newItem As New ListViewItem(weight.Text)
newItem.SubItems.Add(weight.Text)
'newItem.SubItems.Add(TextBox3.Text)
ListBox1.Items.Add(newItem)
ListView1.Items.Add(newItem)
rowcnt.Text = ListView1.Items.Count
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Timer1.Enabled = True
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
' ExportDatasetToCsv(List)
'WriteToTextFile()
Me.DoSave()
End Sub
Private Sub DoSave()
Dim SFD As New SaveFileDialog()
Try
With SFD
.AddExtension = True
.CheckPathExists = True
.CreatePrompt = False
.OverwritePrompt = True
.ValidateNames = True
.ShowHelp = True
.DefaultExt = "txt"
.Filter = _
"CSV Files (*.csv)|*.csv|" & _
"All files|*.*"
.FilterIndex = 1
If .ShowDialog() = Windows.Forms.DialogResult.OK Then
Me.DoSaveItems(.FileName)
End If
End With
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Exclamation, Me.Text)
End Try
End Sub
' save All values from ListView1
Private Sub DoSaveItems(ByVal fileName As String)
If fileName Is Nothing = False Then
If fileName.Length > 0 Then
Using writer As New System.IO.StreamWriter(fileName)
For Each currentItem As Object In Me.ListView1.Items
writer.Write(currentItem.ToString() & ",")
Next
End Using
End If
End If
End Sub
Public Function ExportListViewToCSV(ByVal filename As String, ByVal lv As ListView) As Boolean
Try
' Open output file
Dim os As New StreamWriter(filename)
' Write Headers
For i As Integer = 0 To lv.Columns.Count - 1
' replace quotes with double quotes if necessary
os.Write("""" & lv.Columns(i).Text.Replace("""", """""") & """,")
Next
os.WriteLine()
' Write records
For i As Integer = 0 To lv.Items.Count - 1
For j As Integer = 0 To lv.Columns.Count - 1
os.Write("""" & lv.Items(i).SubItems(j).Text.Replace("""", """""") + """,")
Next
os.WriteLine()
Next
os.Close()
Catch ex As Exception
' catch any errors
Return False
End Try
Return True
End Function
Public Sub TestExportToCSV()
Dim dlg As New SaveFileDialog
dlg.Filter = "CSV files (*.CSV)|*.csv"
dlg.FilterIndex = 1
dlg.RestoreDirectory = True
If dlg.ShowDialog = Windows.Forms.DialogResult.OK Then
If ExportListViewToCSV(dlg.FileName, ListView1) Then
Process.Start(dlg.FileName)
End If
End If
End Sub
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
'TestExportToCSV()
End Sub
End Class
''''
As you haven't shown us your code, we can't tell you how to modify it specifically. In general though, you can treat the ListView somewhat like a 2D array, looping through the rows and the columns to get the data. That means that you could output the data to a CSV like this:
Using writer As New StreamWriter(filePath)
For rowIndex = 0 To myListView.Items.Count - 1
Dim item = myListView.Items(rowIndex)
'Write a line break before all but the first line.
If rowIndex > 0 Then
writer.WriteLine()
End If
For columnIndex = 0 To myListView.Columns.Count - 1
Dim subItem = item.SubItems(columnIndex)
'Write a field delimiter before all but the first field.
If columnIndex > 0 Then
write.Write(",")
End If
writer.Write(subItem.Text)
Next
Next
End Using
That's the old-school way. There are more succinct options, especially with the advent of LINQ:
File.WriteAllLines(filePath,
myListView.Items.
Cast(Of ListViewItem)().
Select(Function(item) String.Join(",",
item.SubItems.
Cast(Of ListViewItem.ListViewSubItem)().
Select(Function(subItem) subItem.Text))))
EDIT:
If you want to include the column headers then you can modify the above code like so:
Using writer As New StreamWriter(filePath)
For columnIndex = 0 To myListView.Columns.Count - 1
Dim column = myListView.Columns(columnIndex)
'Write a field delimiter before all but the first field.
If columnIndex > 0 Then
writer.Write(",")
End If
writer.Write(column.Text)
Next
For rowIndex = 0 To myListView.Items.Count - 1
Dim item = myListView.Items(rowIndex)
'Write a line break before each line.
writer.WriteLine()
For columnIndex = 0 To myListView.Columns.Count - 1
Dim subItem = item.SubItems(columnIndex)
'Write a field delimiter before all but the first field.
If columnIndex > 0 Then
writer.Write(",")
End If
writer.Write(subItem.Text)
Next
Next
End Using
File.WriteAllLines(filePath,
myListView.Items.
Cast(Of ListViewItem)().
Select(Function(item) String.Join(",",
item.SubItems.
Cast(Of ListViewItem.ListViewSubItem)().
Select(Function(subItem) subItem.Text))).
Prepend(String.Join(",",
myListView.Columns.
Cast(Of ColumnHeader)().
Select(Function(header) header.Text))))

How to make a program that would detect the same characters within two strings

so i made this but when i enter a string it would only detect one character
and it wont convert the entered string to lower case too
Dim readme, readme2 As String
Dim j, i As Integer
Dim Compare As Integer
readme = TextBox1.Text
readme2 = TextBox2.Text
readme.ToLower.Substring(i, readme.Length)
readme2.ToLower.Substring(j, readme2.Length)
For i = 0 To readme.Length
For j = 0 To readme2.Length
If readme = readme2 Then
Compare = +1
End If
Next
Next
Label4.Text = Compare`enter code here`
Strings are immutable. You cannot apply a method to a string and expects that string to change in response to the inner operations of that method.
You need to reassign the result of the operation to the same string that you have used to call the method
readme = readme.ToLower()
readme2 = readme2.ToLower()
The second part of your question is more confused, are you trying to count the number of equal chars in the same position?
In that case your loop should be
Dim maxLenToCheck = Math.Min(readme.Length, readme2.Length)
For i = 0 To maxLenToCheck - 1
If readme(i) = readme2(i) Then
Compare += 1
End If
Next
In that loop you set always the Compare to 1, the correct syntax to increment the Compare variable is
Compare += 1
Following your comment below, then I presume that your loop should be written as
Dim Compare = 0
For i = 0 To readme.Length - 1
for j = 0 to readme2.Length -1
If readme(i) = readme2(j) AndAlso _
Not Char.IsWhiteSpace(readme(i)) Then
Compare += 1
End If
Next
Next
Based on the comments in the solution by Steve, the author wants to know the count of letters occurring in both strings, ignoring case and white spaces.
By my count, however, the solution should be 21, not 20. Here is a solution using LINQ that also gives visual feedback on where those letters are located:
Public Class Form1
Private Class LetterCount
Public Letter As Char
Public Count As Integer
Public Overrides Function ToString() As String
Return Letter & " : " & Count
End Function
End Class
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
TextBox1.Text = "This is a Test"
TextBox2.Text = "This should be tryed before"
RichTextBox1.ReadOnly = True
RichTextBox1.Font = New Font("MS Courier", 14) ' monospaced font
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
RichTextBox1.Text = TextBox1.Text & vbCrLf & TextBox2.Text & vbCrLf
Dim charsA As New List(Of Char)(TextBox1.Text.ToLower.ToCharArray.Where(Function(x) Not Char.IsWhiteSpace(x)))
Dim charsB As New List(Of Char)(TextBox2.Text.ToLower.ToCharArray.Where(Function(x) Not Char.IsWhiteSpace(x)))
Dim DistinctCommonLetters = (From A In charsA, B In charsB Where A = B Select A).Distinct
Dim DistinctCounts =
From Letter In DistinctCommonLetters, C In charsA.Concat(charsB)
Where C = Letter
Group By Letter Into Group
Select New LetterCount With {.Letter = Letter, .Count = Group.Count}
Dim TotalMatches = DistinctCounts.Sum(Function(x) x.Count)
ListBox1.DataSource = DistinctCounts.ToList
Label1.Text = "TotalMatches: " & TotalMatches
End Sub
Private Sub ListBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ListBox1.SelectedIndexChanged
Dim LC As LetterCount = ListBox1.SelectedItem
RichTextBox1.SelectAll()
RichTextBox1.SelectionColor = Color.Black
Dim index As Integer = RichTextBox1.Find(LC.Letter, 0, RichTextBoxFinds.None)
While index <> -1
RichTextBox1.Select(index, 1)
RichTextBox1.SelectionColor = Color.Red
index = RichTextBox1.Find(LC.Letter, index + 1, RichTextBoxFinds.None)
End While
End Sub
End Class

VB.NET Read text file line by line and set every line in textbox with button clicks

hello i want to read text file line by line and set every lien in textbox eash time i click the button
this is my code and working fine. but i looking for easy way to read large text that has more thean 5 lines ?
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Static count As Integer
count = count + 1
Dim textfile As String = "c:\test.txt"
If IO.File.Exists(textfile) Then
Dim readLines() As String = IO.File.ReadAllLines(myFile)
If count = 1 Then
TextBox1.Text = readLines(0)
End If
If count = 2 Then
TextBox1.Text = readLines(1)
End If
If count = 3 Then
TextBox1.Text = readLines(2)
End If
If count = 4 Then
TextBox1.Text = readLines(3)
End If
If count = 5 Then
TextBox1.Text = readLines(4)
End If
If count = 6 Then
TextBox1.Text = readLines(5)
End If
End If
End Sub
I think you need to read the file just one time when you load your form (assuming a WinForms example here)
' Declare these two globally
Dim readLines() As String
Dim count As Integer = 0
Private void Form_Load(sender As Oject, e As EventArgs) Handles Base.Load
' In form load, read the file, just one time
Dim textfile As String = "c:\test.txt"
If IO.File.Exists(textfile) Then
readLines() As String = IO.File.ReadAllLines(myFile)
else
TextBox1.Text "File not found"
End If
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
' Check if you have a file and if you don't have reached the last line
if readLines IsNot Nothing AndAlso count < readLines.Length Then
TextBox1.Text = readLines(count)
count += 1
else
TextBox1.Text "End of file"
End If
End Sub
This reduces the amount of code you need to write:
TextBox1.Text = readLines(count - 1)

I'm trying to read a .txt DataGridView in VB Express 2010 and search for contents. How do I do it? (content is relevant)

This is my first time on this site and I would like help very much.
I made a program in VB 2010 Express to try and read a .txt file into an DataGridView. I got it to read in and I have a function to search through surnames and search through date of birth. The way I want it to search is so that if I type in the month (02) for February, then it will list all the people with the DOB month as February. The surnames work fine but the DOB doesn't. Whenever I try to search the month February (02) The DataGridView becomes blank. http://puu.sh/8asUD.png (picture of addressgrid/datagridview going blank) The contents of the .txt file are exactly:
Jackson,Samantha,2 Heather Row,Basingstoke,RG21 3SD,01256 135434,23/04/1973,sam.jackson#hotmail.com,Vickers,Jonathan,18 Saville Gardens,Reading,RG3 5FH,01196 678254,04/02/1965,the_man#btinternet.com,Morris,Sally,The Old Lodge, Hook,RG23 5RD,01256 728443,19/02/1975,smorris#fgh.co.uk,Cobbly,Harry,345 The High Street,Guildford,GU2 4KJ,01458 288763,30/03/1960,harry.cobbly#somewhere.org.uk,Khan,Jasmine,36 Hever Avenue,Edenbridge,TN34 4FG,01569 276524,28/02/1980,jas.khan#hotmail.com,Vickers,Harriet,45 Sage Gardens,Brighton,BN3 2FG,01675 662554,04/04/1968,harriet.vickers#btinternet.com
Here's the code for THE ENTIRE FORM:
Public Class AddressBook
Structure Address
Public Forename As String
Public Surname As String
Public Address1 As String
Public Address2 As String
Public Postcode As String
Public Phonenumber As String
Public DOB As String
Public Email As String
End Structure
Public Addressbook(40) As Address
Public recordcounter As Integer = 0
Public readfile As Boolean = False
Private Sub btt_read_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btt_read.Click
'Declare Textfile
If System.IO.File.Exists("addressbook.txt") = False Then
MsgBox("This text file doesn't exist")
End If
Dim Addressfile As New System.IO.StreamReader("C:\Users\DirtyMike\Desktop\123\Controlled Assessment\addressbook.txt", True)
Dim loopcounter As Integer
Dim filecontent As String
Dim temparray() As String
If readfile = False Then
filecontent = Addressfile.ReadLine
temparray = filecontent.Split(",")
readfile = True
'Display the data
For loopcounter = 0 To (temparray.Length - 7) Step 8
Addressbook(recordcounter).Surname = temparray(loopcounter + 0)
Addressbook(recordcounter).Forename = temparray(loopcounter + 1)
Addressbook(recordcounter).Address1 = temparray(loopcounter + 2)
Addressbook(recordcounter).Address2 = temparray(loopcounter + 3)
Addressbook(recordcounter).Postcode = temparray(loopcounter + 4)
Addressbook(recordcounter).Phonenumber = temparray(loopcounter + 5)
Addressbook(recordcounter).DOB = temparray(loopcounter + 6)
Addressbook(recordcounter).Email = temparray(loopcounter + 7)
recordcounter = recordcounter + 1
Next
Addressfile.Close()
REM Display the Data
For loopcounter = 0 To recordcounter - 1
AddressGrid.Rows.Add()
AddressGrid.Rows.Item(loopcounter).Cells(0).Value = Addressbook(loopcounter).Surname
AddressGrid.Rows.Item(loopcounter).Cells(1).Value = Addressbook(loopcounter).Forename
AddressGrid.Rows.Item(loopcounter).Cells(2).Value = Addressbook(loopcounter).Address1
AddressGrid.Rows.Item(loopcounter).Cells(3).Value = Addressbook(loopcounter).Address2
AddressGrid.Rows.Item(loopcounter).Cells(6).Value = Addressbook(loopcounter).DOB
AddressGrid.Rows.Item(loopcounter).Cells(7).Value = Addressbook(loopcounter).Email
AddressGrid.Rows.Item(loopcounter).Cells(5).Value = Addressbook(loopcounter).Phonenumber
AddressGrid.Rows.Item(loopcounter).Cells(4).Value = Addressbook(loopcounter).Postcode
Next
'Display the data from the file.
End If
End Sub
Private Sub bttsurname_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btt_searchsur.Click
AddressGrid.Rows.Clear()
Dim surname As String
Dim loopcounter As Integer
Dim positioncounter As Integer
surname = txt_surname.Text
For loopcounter = 0 To recordcounter
If Addressbook(loopcounter).Surname = surname Then
Me.AddressGrid.Rows.Add()
Me.AddressGrid.Rows.Item(positioncounter).Cells(0).Value = Me.Addressbook(loopcounter).Surname
Me.AddressGrid.Rows.Item(positioncounter).Cells(1).Value = Me.Addressbook(loopcounter).Forename
Me.AddressGrid.Rows.Item(positioncounter).Cells(2).Value = Me.Addressbook(loopcounter).Address1
Me.AddressGrid.Rows.Item(positioncounter).Cells(3).Value = Me.Addressbook(loopcounter).Address2
Me.AddressGrid.Rows.Item(positioncounter).Cells(4).Value = Me.Addressbook(loopcounter).Postcode
Me.AddressGrid.Rows.Item(positioncounter).Cells(5).Value = Me.Addressbook(loopcounter).Phonenumber
Me.AddressGrid.Rows.Item(positioncounter).Cells(6).Value = Me.Addressbook(loopcounter).DOB
Me.AddressGrid.Rows.Item(positioncounter).Cells(7).Value = Me.Addressbook(loopcounter).Email
positioncounter = positioncounter + 1
End If
Next
End Sub
Private Sub btt_menu_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btt_menu.Click
Menu1.Show()
Me.Close()
End Sub
Private Sub btt_searchdob_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btt_searchdob.Click
AddressGrid.Rows.Clear()
Dim DOB As String
Dim loopcounter, positioncounter As Integer
Dim MonthA As String
DOB = txt_DOB.Text
MonthA = Mid(DOB, 4, 2)
positioncounter = 0
For loopcounter = 0 To recordcounter
If MonthA = Mid(Addressbook(loopcounter).DOB, 4, 2) Then
Me.AddressGrid.Rows.Add()
Me.AddressGrid.Rows.Item(positioncounter).Cells(0).Value = Me.Addressbook(loopcounter).Surname
Me.AddressGrid.Rows.Item(positioncounter).Cells(1).Value = Me.Addressbook(loopcounter).Forename
Me.AddressGrid.Rows.Item(positioncounter).Cells(2).Value = Me.Addressbook(loopcounter).Address1
Me.AddressGrid.Rows.Item(positioncounter).Cells(3).Value = Me.Addressbook(loopcounter).Address2
Me.AddressGrid.Rows.Item(positioncounter).Cells(4).Value = Me.Addressbook(loopcounter).Postcode
Me.AddressGrid.Rows.Item(positioncounter).Cells(5).Value = Me.Addressbook(loopcounter).Phonenumber
Me.AddressGrid.Rows.Item(positioncounter).Cells(6).Value = Me.Addressbook(loopcounter).DOB
Me.AddressGrid.Rows.Item(positioncounter).Cells(7).Value = Me.Addressbook(loopcounter).Email
positioncounter = positioncounter + 1
End If
Next
End Sub
Private Sub btt_clear_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btt_clear.Click
AddressGrid.Rows.Clear()
For loopcounter = 0 To recordcounter - 1
AddressGrid.Rows.Add()
AddressGrid.Rows.Item(loopcounter).Cells(0).Value = Addressbook(loopcounter).Surname
AddressGrid.Rows.Item(loopcounter).Cells(1).Value = Addressbook(loopcounter).Forename
AddressGrid.Rows.Item(loopcounter).Cells(2).Value = Addressbook(loopcounter).Address1
AddressGrid.Rows.Item(loopcounter).Cells(3).Value = Addressbook(loopcounter).Address2
AddressGrid.Rows.Item(loopcounter).Cells(4).Value = Addressbook(loopcounter).Postcode
AddressGrid.Rows.Item(loopcounter).Cells(5).Value = Addressbook(loopcounter).Phonenumber
AddressGrid.Rows.Item(loopcounter).Cells(6).Value = Addressbook(loopcounter).DOB
AddressGrid.Rows.Item(loopcounter).Cells(7).Value = Addressbook(loopcounter).Email
Next
'Display the data from the file.
End Sub
Private Sub Form3_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
End Sub
End Class
Any help would be greatly appreciated. Thanks in advance! (P.S. Apologies for the poor tags, they're probably wrong.)
If you can add some Symbol into the text this process will be easy to fetch Like:
TextFileData = %Your Name,Age,Address%Other Name, Other Age, Other Address,
You can use split ("%") to get the users information
Users = TextFileData.Split("%")
Then use split(",") to extract the information
Information = Users(0),Split(",")

sequential access file in vb

I am working on a program in Visual Basic that incorporates using a sequential access file for a ballot type program. Each type the user clicks the save vote button, the amount of votes gets stored. What I am trying to do is in my access file is to display the number of votes as an actual number. The way my program is written right now, the name of the candidate appears as many times as the vote was saved. for example, if perez was voted for 4 times, in the access file perez is displayed on 4 different lines. How do I display the actual number of how many time they were voted for. I'm thinking using a counter variable, but not really sure how to really implement it in. this is what i have so far.
Public Class Voter
Dim file As IO.File
Dim infile As IO.StreamReader
Dim outfile As IO.StreamWriter
Private Sub Voter_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
outfile = IO.File.CreateText("Votes.txt")
End Sub
Private Sub btnVote_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnVote.Click
lstResult.Items.Clear()
'which buttons is clicked
If radMark.Checked = True Then
outfile.WriteLine(radMark.Text)
radMark.Checked = False
ElseIf radSheima.Checked = True Then
outfile.WriteLine(radSheima.Text)
radSheima.Checked = False
ElseIf radSam.Checked = True Then
outfile.WriteLine(radSam.Text)
radSam.Checked = False
Else
MessageBox.Show("You should select one among them")
End If
End Sub
Private Sub btnResult_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnResult.Click
'Dim Mark, Sheima, Sam As Integer
Dim Mark As Integer = 0
Dim Sheima As Integer = 0
Dim Sam As Integer = 0
Dim name As String
'Mark = Sheima = Sam = 0
outfile.Close()
infile = IO.File.OpenText("Votes.txt")
'keep track of votes
While Not infile.EndOfStream
name = infile.ReadLine()
If name.Equals("Mark Stone") Then
Mark += 1
ElseIf name.Equals("Sheima Patel") Then
Sheima += 1
Else
Sam += 1
End If
End While
'results
lstResult.Items.Clear()
lstResult.Items.Add("Mark Stone " & CStr(Mark))
lstResult.Items.Add("Shemia Patel " & CStr(Sheima))
lstResult.Items.Add("Sam Perez " & CStr(Sam))
infile.Close()
End Sub
Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
Me.Close()
End Sub
End Class
In your btnVote_Click function you are writing the radiobutton text into the file everytime you click on it, that's how the issue to be created.
Also you are counting how many times the name appears in the file as the number of vote but not the number.
You should try putting the name and count in your vote file rather than just the name, e.g.
Mark,1
Sheima,2
Same,5
Then when you click Vote button, you should read the number for Mark, increment by 1 and write it back.
Try this,
Private Sub btnVote_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnVote.Click
lstResult.Items.Clear()
'which buttons is clicked
If radMark.Checked = True Then
AddCount(radMark.Text)
radMark.Checked = False
ElseIf radSheima.Checked = True Then
AddCount(radSheima.Text)
radSheima.Checked = False
ElseIf radSam.Checked = True Then
AddCount(radSam.Text)
radSam.Checked = False
Else
MessageBox.Show("You should select one among them")
End If
End Sub
Private Sub btnResult_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnResult.Click
'results
lstResult.Items.Clear()
lstResult.Items.Add("Mark Stone " & GetCount(radMark.Text))
lstResult.Items.Add("Shemia Patel " & CStr(radSheima.Text))
lstResult.Items.Add("Sam Perez " & CStr(radSam.Text))
End Sub
Private Sub AddCount(Byval VoteName As String)
infile = New IO.File.StreamReader("Votes.txt")
Dim whole_line As String
Dim person As String
Dim vote_count As Integer
Dim found as boolean
'read through the whole file until the end or find the name
Do While infile.Peek() >= 0 And person <> VoteName
'read each line
whole_line = infile.ReadLine
person = Split(whole_line, ",")(0)
If person = VoteName Then
vote_count = Split(whole_line, ",")(1)
found = True
End If
Loop
'Close the file after it is used.
infile.Close()
'Reopen the file with the StreamWriter
outfile = IO.File.OpenText("Votes.txt")
If found = True Then
'the line will only be replace if the person name is found in the line
whole_line = Whole_line.replace(VoteName & "," & vote_count, VoteName & "," & vote_count + 1)
'Write back into the file
outfile.WriteLine(whole_line)
Else
'if the vote name is not found in the file
'Then create a new one
outfile.WriteLine(VoteName & ",1" & VbCrLf)
End If
outfile.Close()
End Sub
Private Function GetCount(Byval VoteName As String)
infile = New IO.File.StreamReader("Votes.txt")
Dim whole_line As String
Dim person As String
Dim vote_count As Integer
'read through the whole file
Do While infile.Peek() >= 0 And person <> VoteName
'read each line
whole_line = infile.ReadLine
person = Split(Whole_line, ",")(0)
If person = VoteName Then
vote_count = Split(whole_line, ",")(1)
End If
Loop
infile.Close()
Return vote_count
End Sub