Performing linear search with two fields from different text files - vb.net

With the current coded i've realised it is mandatory to have separate text files instead of one text file for my computer science coursework. Searching and reading fields from one text file is simple enough for me, but i'm struggling to search two separate text files and displaying them within text boxes. The array of both files also increase in size when i input data of customer. The text files have several fields. The IF statements do the same thing but they are doing it via different search functions, is their any way i can do it through the same search regarding its coming from two different files?
Some of the text file contents:
1 text file:
1 7 LL11 3BY C Brymbo
DwellingID - House num - postcode - tax band - Ward
the other text file:
2 James King 06/06/1999 YJames07#gmail.com uOI4gSqohd
customerID - F.name - L.name - DOB - Contact info - Password
This is for the click event, which is related to a linear search class:
Private Sub btnsearch_Click(sender As Object, e As EventArgs) Handles btnsearch.Click
If cbsearch.Text = "View customer details" Then
customerrecord = linsearchCustomerId(customerobject, txtsearchdetails.Text)
If customerrecord.firstname = "" Then 'Validation, if nothing has been entered a messagebox will appear notifying the user
MsgBox("No customers found")
Else
lblCustID.Text = customerrecord.CustomerID 'put the field within the label or textbox designated
txtfirstname.Text = customerrecord.firstname
txtlastname.Text = customerrecord.lastname
txtvote.Text = customerrecord.Eligibletovote
txtcontactinfo.Text = customerrecord.contactinfo
txtdob.Text = customerrecord.DOB
lblpassword.Text = customerrecord.password
End If
End If
If cbsearch.Text = "View customer details + dwelling" Then
dwellrecord = dwellingdetailsearch(dwellingObject, txtsearchdetails.Text)
If dwellrecord.dwellingID = "" Then
MsgBox("Dwelling details not found")
Else
lbldwellingid.Text = dwellrecord.dwellingID
txthousenum.Text = dwellrecord.housenum
txtaddress.Text = dwellrecord.address
ComboBox1.Text = dwellrecord.taxband
Cbward.Text = dwellrecord.wardname
End If
End If
End Sub
Here is the code of reading to text files:
Function getalllines() As String()
Dim filedata() As String = IO.File.ReadAllLines(Dir$(_CLfilename))
Return filedata
End Function

Related

How to display my data from a text-file determined by a combo box?

I am trying to retrieve a surfer from a list on a textfile, the user selects the surfer from the combo box which then displays that surfers data in a bunch of labels. My code requires each surfer to have an ID for it to be able to know which record to retrieve from the database. However when I try to put my ID from my loop together with each surfers name, I receive an error saying "Conversion from string to type 'Long' is not valid." I have tried different methods of getting around this, none of which have worked. Here is my code:
Private Sub Lookup_Load(sender As Object, e As EventArgs) Handles MyBase.Load
madelabel = False
For i = 1 To maxrecJudge
FileGet(2, ajudge, i)
recnoJudge = i
judgename = recnoJudge And " " And ajudge.name
cmbJudge.Items.Add(judgename)
Next i
For i = 1 To maxrecSurfer
FileGet(1, asurfer, i)
recnoSurfer = i
surfername = recnoSurfer And " " And asurfer.name
cmbSurfer.Items.Add(surfername)
Next i
End Sub
Private Sub cmbSurfer_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cmbSurfer.SelectedIndexChanged
recnoSurfer = CInt(Val(New Text.StringBuilder((From ch In cmbSurfer.Text.ToCharArray Where IsNumeric(ch)).ToArray).ToString))
FileGet(1, asurfer, recnoSurfer)
If madelabel = False Then
lblName = New Label
lblName.Top = 160
lblName.Left = 253
lblName.Autosize = True
lblName.Text = asurfer.name
Me.Controls.Add(lblName)
End Sub
For simplicity I have only included one label creation above, but there are several labels spawned each with data of the surfer.
Am I on the right track with this? In the second sub my code extracts the integer (ID) from the combo box which then is used as a record number to find the rest of the data. The error relates to these lines:
surfername = recnoSurfer And " " And asurfer.name
cmbSurfer.Items.Add(surfername)
It won't let me concatenate the ID and the surfers name. Any help?
If you are doing a lot of concatenation, use a StringBuilder. It is far quicker. Every time you concatenation strings, a new string is created. Over a large amount of iterations, StringBuilder is the better choice.

vb.net - Comparing two text files and retrieving a specific value

this question is related to my previous questions
I'm currently working on a Registration form where all the details of a student are save in a text file.
I populated the combobox using a textfile.
The format of these values are for example: (code~school name) SCH001~Saint
Thomas College
this is how I saved the details in a text file:
Dim firstname, lastname, email, mobile, level, currentschool, currenttrack, institution1, institution2, institution3, institution4, institution5, institution6, courses1, courses2, courses3, macaddress, eventcode, idseq, filename, logfiledirectory, targetdirectory, log, configdir, printschool As String
firstname = txtFName.Text
lastname = txtLName.Text
email = txtEmail.Text
mobile = txtMobile.Text
level = cmbLevel.Text
currenttrack = cmbCurrentTrack.Text
printschool = cmbCurrentSchool.Text
currentschool = cmbCurrentSchool.SelectedValue
institution1 = cmbInstitution1.SelectedValue
institution2 = cmbInstitution2.SelectedValue
institution3 = cmbInstitution3.SelectedValue
institution4 = cmbInstitution4.SelectedValue
institution5 = cmbInstitution5.SelectedValue
institution6 = cmbInstitution6.SelectedValue
courses1 = cmbCourse1.SelectedValue
courses2 = cmbCourse2.SelectedValue
courses3 = cmbCourse3.SelectedValue
If mobile = "" Then
mobile = "09000000000"
End If
If firstname = "" Or lastname = "" Or email = "" Or level = "" Or currentschool = "" Or currenttrack = "" Then
MessageBox.Show("Please enter the required fields!", "Registration", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
I have a datagridview where all the saved details in a text file are shown.
here's a screenshot of my datagridview:
WHAT I WANT TO DO: I want to retrieve the School name using the current school code (refer to the image) from the source text file(the one I used to populated my comboboxes). Instead of the school code, I want the School name to be shown in the datagridview.
Is there a possible way to do it?
I hope you guys understand what im trying to say.
Im new here.
Again just like I answered last time, use this function:
Function FetchSchoolName(schoolcode As String, filepath As String) As String
Dim filecontents = File.ReadAllLines(filepath)
For Each line As String In filecontents
If (line.Contains(schoolcode.Trim())) Then
Return line.Split("~"c)(1)
End If
Next
Return String.Empty
End Function
Example text entry:
sch001~abcinstitute
sch002~myacademy
sch003~someschoolname
Then pass the schoolcode(which you get from the datagridview) and filepath in the top-most function
MessageBox.Show(FetchSchoolName("sch002", "C:\Users\nobody\Desktop\somefile.txt"))
Output:
myacademy
Now in respect to your DataGridView, wherever you are filling(source binding) it use the above method
If you want to produce the same output as Nobody's answer but without looping, you can use LINQ, this also uses less lines of code but achieves the same output
Dim query = filecontents.Where(Function(x) x.Contains(schoolcode)).Select(Function(x) x.Split("~")(1)).FirstOrDefault
Return query.ToString()

How to find and delete matching words in two different text files in VB?

Its a wordy question, but basically I want to have VB check textfile1 for matching words in textfile2, and then delete all instances of similar words in textfile2 and output the results as results.txt.
Outputting results shouldn't be too difficult, but i'm unsure on where to proceed when it comes to recognizing similar wordage. Also, would it be possible to set up a whitelist (there's going to be one word repeated over and over - which I don't want deleted).
This is my open file / read file dialogue which I use for both prompts, and both are displayed visually in a textbox.
Sub Maplist()
If txtFile.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
Dim sr As New System.IO.StreamReader(txtFile.FileName)
tbx1.Text = sr.ReadToEnd
sr.Close()
End If
Thanks for any help!
Edit:
A sample of the first text file looks like this:
map_01, 200/250
map_03, 358/450
map_06, 528/2000
The second file looks like:
map_01
map_02
map_03
map_04
map_05
map_06
Basically the second file is the "master list'. I want the program to recognize a matching word between both files (for instance, the 01 in map_01) and then delete the entry from the master list. When I was talking about whitelisting I was concerned that it would match a word like"map" and delete everything in the master list. I didn't wanted it to delete the whole word just because it matched "map"
You have to make an array of words from both the TextFile and compare those. I did it for you here:
Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click
'make array of words from both the files
Dim text1Array() As String = TextBox1.Text.Split(" ")
Dim text2Array() As String = TextBox2.Text.Split(" ")
Dim NewText As String
NewText = TextBox2.Text
'loop through all the words in first array
For i = 0 To text1Array.Length - 1
'loop through all the words in second array
For j = 0 To text2Array.Length - 1
'match the words
If text1Array(i) = text2Array(j) Then
'replace the found word with an empty character
NewText = NewText.Replace(text2Array(j), String.Empty)
'delete double space
NewText = NewText.Replace(" ", " ")
End If
Next
Next
'save it into third textbox
TextBox3.Text = NewText
End Sub
I checked it like this:
Textbox1 contained :
one two three four five six seven eight nine ten eleven twelve
TextBox2 contained :
one subaz three sarma five loves six coding eight ten all the twelve time
After clicking the button, TextBox3 contained:
subaz sarma loves coding all the time
This works perfectly fine.
Now, about the whitelist, let's say you don't want to remove "five" even if it's matched. Do this:
Dim WhiteListWord As String = "five"
And change the condition as :
If text1Array(i) = text2Array(j) And text1Array(i) <> WhiteListWord Then
New output in the textbox3 will be :
subaz sarma five loves coding all the time

How can i check for a character after certain text within a listbox?

How can i check for a character after other text within a listbox?
e.g
Listbox contents:
Key1: V
Key2: F
Key3: S
Key4: H
How do I find what comes after Key1-4:?
Key1-4 will always be the same however what comes after that will be user defined.
I figured out how to save checkboxes as theres only 2 values to choose from, although user defined textboxes is what im struggling with. (I have searched for solutions but none seemed to work for me)
Usage:
Form1_Load
If ListBox1.Items.Contains("Key1: " & UsersKey) Then
TextBox1.Text = UsersKey
End If
Which textbox1.text would then contain V / whatever the user defined.
I did try something that kind of worked:
Form1_Load
Dim UsersKey as string = "V"
If ListBox1.Items.Contains("Key1: " & UsersKey) Then
TextBox1.Text = UsersKey
End If
but i'm not sure how to add additional letters / numbers to "V", then output that specific number/letter to the textbox. (I have special characters blocked)
Reasoning I need this is because I have created a custom save settings which saves on exit and loads with form1 as the built in save settings doesn't have much customization.
e.g Can't choose save path, when filename is changed a new user.config is generated along with old settings lost.
Look at regular expressions for this.
Using the keys from your sample:
Dim keys As String = "VFSH"
Dim exp As New RegEx("Key[1-4]: ([" & keys& "])")
For Each item As String in ListBox1.Items
Dim result = exp.Match(item)
If result.Success Then
TextBox1.Text = result.Groups(1).Value
End If
Next
It's not clear to me how your ListBoxes work. If you might find, for example, "Key 2:" inside ListBox1 that you need to ignore, you will want to change the [1-4] part of the expression to be more specific.
Additionally, if you're just trying to exclude unicode or punctuation, you could also go with ranges:
Dim keys As String = "A-Za-z0-9"
If you are supporting a broader set of characters, there are some you must be careful with: ], \, ^, and - can all have special meanings inside of a regular expression character class.
You have multiple keys, I assume you have multiple textboxes to display the results?
Then something like this would work. Loop thru the total number of keys, inside that you loop thru the alphabet. When you find a match, output to the correct textbox:
Dim UsersKey As String
For i As Integer = 1 To 4
For Each c In "ABCDEFGHIJKLMNOPQRSTUVWXYZ".ToCharArray()
UsersKey = c
If ListBox1.Items.Contains("Key" & i & ": " & UsersKey) Then
Select Case i
Case 1
TextBox1.Text = UsersKey
Case 2
TextBox2.Text = UsersKey
Case 3
TextBox3.Text = UsersKey
Case 4
TextBox4.Text = UsersKey
End Select
Exit For 'match found so exit inner loop
End If
Next
Next
Also, you say your settings are lost when the filename is changed. I assume when the version changes? The Settings has an upgrade method to read from a previous version. If you add an UpgradeSettings boolean option and set it to True and then do this at the start of your app, it will load the settings from a previous version:
If My.Settings.UpgradeSettings = True Then
My.Settings.Upgrade()
My.Settings.Reload()
My.Settings.UpgradeSettings = False
My.Settings.Save()
End If
Updated Answer:
Instead of using a listtbox, read the settings file line by line and output the results to the correct textbox based on the key...something like this:
Dim settingsFile As String = "C:\settings.txt"
If IO.File.Exists(settingsFile) Then
For Each line As String In IO.File.ReadLines(settingsFile)
Dim params() As String = Split(line, ":")
If params.Length = 2 Then
params(0) = params(0).Trim
params(1) = params(1).Trim
Select Case params(0)
Case "Key1"
Textbox1.Text = params(1)
Case "Key2"
Textbox2.Text = params(1)
End Select
End If
Next line
End If
You can associate text box with a key via its Name or Tag property. Lets say you use Name. In this case TextBox2 is associated with key2. TextBox[N] <-> Key[N]
Using this principle the code will look like this [considering that your list item is string]
Sub Test()
If ListBox1.SelectedIndex = -1 Then Return
Dim data[] As String = DirectCast(ListBox1.SelectedItem, string).Split(new char(){":"})
Dim key As String = data(0).Substring(3)
Dim val As String = data(1).Trim()
' you can use one of the known techniques to get control on which your texbox sits.
' I omit this step and assume "Surface1" being a control on which your text boxes sit
DirectCast(
(From ctrl In Surface1.Controls
Where ctrl.Name = "TextBox" & key
Select ctrl).First()), TextBox).Text = val
End Sub
As you can see, using principle I just explained, you have little parsing and what is important, there is no growing Select case if, lets say, you get 20 text boxes. You can add as many text boxes and as many corresponding list items as you wish, the code need not change.

How to compare combobox value with items in listbox - vb.net

I have a combo box and a listbox.
All i want is, when i select a value(text) from the combobox to check if there is a same value(same text) at the listbox and if there is, then msgbox should display as "DATA FOUND"
i tried this code, but its not working
Dim i As Integer
For i = 0 To ListBox1.Items.Count - 1
If ComboBox1.SelectedItem = ListBox1.ValueMember Then
MsgBox("DATA FOUND")
End If
Next i
Thanks in advance....
You are using two properties with a different meaning for your comparison.
SelectedItem is an object (could be anything depending on how you have filled the combo, ValueMember is just the name of a property to use as the actual value for the items in the ListBox.
However the two classes (ListBox and ComboBox) share the same pattern for storing their list items, so supposing that both are populated using a list of strings then your code could be
Dim curComboItem = ComboBox1.SelectedItem.ToString()
For i = 0 To ListBox1.Items.Count - 1
If curComboItem = ListBox1.Items(i).ToString() Then
MsgBox("DATA FOUND")
Exit For
End If
Next i
If ComboBox1.SelectedItem = ListBox1.ValueMember Then
should be
If ComboBox1.SelectedItem = ListBox1.Items(i) Then
Notice that
ComboBox1.SelectedItem
only works for items inside of the Collection. You can extend this to any text by the
.text
parameter.
P.D.
Next i '???
Using real objects in your ComboBox and ListBox can often lead to better flexibility of your application.
For example, you have a car lot application, in which you have long list of available cars and you don't want to browse the entire list - you use ComboBox to select make and model, and do something with the items in your list box.
(in pseudo-code)
Your car object.
class Car
ModelId
ModelMake
ModelName
FullName = ModelMake & " " & ModelName
End Class
class AvailableCar Inherits Car
IsOnTheLot
VIN
Price
'etc
End Class
In your Form class
comboCarMakes.DataSource = GetListOfMakesOfCars() ' List of Car classes
comboCarMakes.ValueMember = "ModelId"
comboCarMakes.DisplayMember = "FullName"
listAvbailableCars.DataSource = GetListOfAvailableCars() ' List of AvailableCar classes
listAvbailableCars.ValueMember = "VIN"
listAvbailableCars.DisplayMember = "FullName"
Sub comboCarMakes_SelectedIndexChanged
Dim car as Car = DirectCast(comboCarMakes.SelectedItem, Car)
For i = 0 To listAvbailableCars.Items.Count - 1
If car.ModelId = DirectCast(listAvbailableCars.Items(i), AvailableCar).ModelId Then
' Do something
End If
Next
End Sub
Advantage - you have lots of information available immediately.