join arrays and find matches - arrays

So i'm working on a project and i've hit a bit of a roadblock. i'm trying to compare two arrays that've been populated with read-in and split text files, find the matches of individual elements (names), then populate a listbox with the resulting matches. here's the code i have so far:
Dim sr As IO.StreamReader
Dim sw As IO.StreamWriter
Dim guest As String()
Dim gift As String()
Private Sub frmTYC_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim strFile1 As String
Dim strFile2 As String
Dim intCount As Integer
strFile1 = "Guests.txt"
strFile2 = "Gifts.txt"
intCount = 0
sr = IO.File.OpenText(strFile1)
Do While sr.Peek <> -1
guest = sr.ReadLine.Split(",")
lstGuests.Items.Add(guest(0))
intCount += 1
Loop
sr.Close()
intCount = 0
sr = IO.File.OpenText(strFile2)
Do While sr.Peek <> -1
gift = sr.ReadLine.Split(",")
lstGifts.Items.Add(gift(1) & " " & "gifted" & " " & gift(0))
intCount += 1
Loop
sr.Close()
End Sub
Private Sub btnList_Click(sender As Object, e As EventArgs) Handles btnList.Click
End Sub
i'm trying to compare guest(0) and gift(1) as those are the names, with guest having all the names and gift having all the names of the people in guest who gave a gift. i need the listbox to be populated on the list button click

Related

How to write items from a ListBox into an Array VBA [duplicate]

I classify myself as a beginner in programing. I have a userform that first looks up a number presented by the user. Example 12345, 12346,12347. The number entered into the textbox is searched for and then added to the listbox as a valid number. After the user enters all the numbers needed, they should be able to click change and update the records accordingly.
Private Sub Change_Click()
Dim i As Long
For i = LBound(RunArray) To UBound(RunArray)
' Code to update each record, still working on it.
Next
End Sub
Private Sub RunNumber_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
Dim RunArray() As String
Dim RunCount As Integer
RunCount = 0
If KeyCode = 13 Then
With Sheets("Sheet1").Range("A:A")
Set RunFind = .Find(What:=RunNumber, _
After:=.Cells(.Cells.count), _
LookIn:=xlValues, _
LookAt:=xlWhole, _
SearchOrder:=xlByRows, _
SearchDirection:=xlNext, _
MatchCase:=False)
If Not RunFind Is Nothing Then
ReDim Preserve RunArray(RunCount)
RunArray(RunCount) = RunNumber.Value
RunNumberList.AddItem RunNumber.Value
RunNumber.Value = ""
RunCount = RunCount + 1
Else
MsgBox "The Run Number you entered was not found, Please the number and try again."
RunNumber.Value = ""
End If
End With
End If
End Sub
Private Sub CreateArrayFromListbox()
Dim nIndex As Integer
Dim vArray() As Variant
' dimension the array first instead of using 'preserve' in the loop
ReDim vArray(ListBox1.ListCount - 1)
For nIndex = 0 To ListBox1.ListCount - 1
vArray(nIndex) = ListBox1.List(nIndex)
Next
End Sub
i have an example how to do it with a combobox, (it's the same with a listbox, just change the name accordingly.
Option Explicit
Private Sub UserForm_Initialize()
Dim i&
Dim Arr()
With Me.ComboBox1
For i = 1 To 1000
.AddItem "Item " & i
Next i
Arr = .List
.Clear
End With
For i = 0 To 999
Debug.Print Arr(i, 0)
Next i
Erase Arr
End Sub
this is just a sample code, in real coding, you won't clear the combobox this early, or erase the array.
The results are shown in the immediate window (alt-F11 , and Ctrl-g).
Note : the array is 2 dimendionned, and 0 based (Option base 1, after Option Explicitcan make the whole module 1-based (arrays start at 1) ).

visual basic array sorting from list box

Hello im having trouble with my code !
we are asked to organize a list of names from a text.txt file the make them show up into a lits box (got that part down :) ) . then from the list box we are asked to create an array and sort that array (using our own sorting method) and organize the names using a button in assending order and another button organizing the array in decending order. the results from the orders names should appear in another list box .
i have gotten only the last name in the list to show up in the second list box but my code has no errors it just wont order the names properly! Help!!!!!
here is my code :)
Public Class FileSort
Dim sr As IO.StreamReader = IO.File.OpenText("C:\Users\Inspiron 15\documents\visual studio 2010\Projects\assigment4 EL\assigment4 EL\names.txt")
Structure names
Dim c As Integer
Dim fullname As String
End Structure
Dim allNames(99) As names
Private Sub btnName_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnName.Click
Do While sr.Peek <> -1
Name = sr.ReadLine
LstNames.Items.Add(Name & " ")
Loop
sr.Close()
End Sub
Private Sub bubbelsort(ByRef names() As System.String, ByVal c As Integer)
c = 0
names(c) = sr.ReadLine()
c = c * 1
For c = 1 To 99 Step +1 '~~~ Addding (Z to A) to the the Listbox
lstOrderedNames.Items.Add(Name & "")'
Next
End Sub
Private Sub BtnAssend_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnAssend.Click
Dim names(99) As String
Dim c As Integer
c = 0
Dim A As Integer
A = 99
names(c) = sr.ToString
c = c + 1
For c = 1 To 99 Step +1 '~~~ Addding (Z to A) to the the Listbox
lstOrderedNames.Items.Add(Name & "")
Next
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnDessend.Click
Dim names(99) As String
Dim c As Integer
c = 0
Dim A As Integer
A = 99
names(c) = sr.ToString
names(A) = sr.ToString
A = A - 1
For A = 99 To 0 Step -1 '~~~ Addding (Z to A) to the the Listbox
lstOrderedNames.Items.Add(Name & "")
Next
End Sub
enter image description here
Since your problem is the sorting algorithm (if I understand this correctly).
At first we need an array.
Dim arr(ListBox1.Items.Count - 1) As String
For i As Integer = 0 To arr.Length - 1
arr(i) = CStr(ListBox1.Items(i))
Next
Next the sorting algorithm. Since you wanted to go with BubbleSort:
Private Sub StringBubbleSort(arr As String)
For i As Integer = 0 To arr.Length - 1
For j As Integer = 0 To arr.Length - 2 - i
If String.Compare(arr(j), arr(j + 1)) > 0 Then
Dim temp As String = arr(j)
arr(j) = arr(i)
arr(i) = temp
End If
Next
Next
End Sub
Then you use this function and copy the array to your second ListBox.
StringBubbleSort(arr)
ListBox2.Items.AddRange(arr)
String.Compare: https://msdn.microsoft.com/de-de/library/84787k22(v=vs.110).aspx
you could use linq
ListBox1.Items.Add("Battle")
ListBox1.Items.Add("Cattle")
ListBox1.Items.Add("apple")
ListBox2.DataSource = (From l In ListBox1.Items
Select l Order By l Ascending).ToList

Moving file contents into an array

Im currently working on getting this piece of code to work so that I can read a text file, move the contents into an array and then display a certain column (such as price)
Imports System.IO
Public Class Form1
Dim FileName As String
Dim i As Integer = 0
Dim Alpha As Integer = 0
Dim Products(31) As String
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
FileName = "Products.txt"
End Sub
Private Sub btnCreateArray_Click(sender As Object, e As EventArgs) Handles btnCreateArray.Click
Using MyReader As New Microsoft.VisualBasic.FileIO.TextFieldParser("Products.txt")
MyReader.TextFieldType = FileIO.FieldType.Delimited
MyReader.SetDelimiters(",")
Dim currentRow As String()
While Not MyReader.EndOfData
currentRow = MyReader.ReadFields()
Dim currentField As String
For Each currentField In currentRow
'MsgBox(currentField)
'txtShowNo.Text = currentField
'txtShowP.Text = i
i = i + 1
Products(i) = currentField
Next
End While
End Using
Do While Alpha <= i
If InStr((txtFileSearch.Text), (Products(Alpha))) Then
lstDisplayFile.Items.Add(Products(Alpha))
Alpha = Alpha + 1
End If
Loop
End Sub
Private Sub btn_Click(sender As Object, e As EventArgs) Handles btn.Click
txtFileSearch.Text = ""
End Sub
Private Sub btnAddToFilePrintFile_Click(sender As Object, e As EventArgs) Handles btnAddToFilePrintFile.Click
Dim Name As String
Dim SName As String
Dim IDNo As Integer
Name = txtName.Text
SName = txtSName.Text
IDNo = txtIDNo.Text
FileOpen(1, FileName, OpenMode.Append) ' create a new empty file & open it in append mode'
WriteLine(1, IDNo, Name, SName) ' Writes a line of data'
FileClose(1)
txtName.Text = ""
txtSName.Text = ""
txtIDNo.Text = ""
txtName.Focus()
End Sub
End Class
The program crashes on this line of code:
lstDisplayFile.Items.Add(Products(Alpha))
along with the following message :
An unhandled exception of type 'System.ArgumentNullException' occurred in System.Windows.Forms.dll
Alpha is my counter, and my thought process behind this was that if the input within the textbox is currently in the array, it will display the completed text in the array.
Here is the current contents within my text file :
"£5.00","50"
"£2.50","30"
If anyone could help me solve this I would be appreciative :)

Cant update a record in a database

I'm making a Homework/Revision program for my coursework. I'm following this tutorial http://www.homeandlearn.co.uk/NET/nets12p9.html on how to make a database but theres something wrong with the my update button (btnUpdate)
Private Sub btnUpdate_Click(sender As Object, e As EventArgs) Handles btnUpdate.Click
txtFirstName.Text = ds.Tables("Users").Rows(inc).Item(1) = txtFirstName.Text
txtSurname.Text = ds.Tables("Users").Rows(inc).Item(2) = txtSurname.Text
txtUsername.Text = ds.Tables("Users").Rows(inc).Item(3) = txtUsername.Text
txtPassword.Text = ds.Tables("Users").Rows(inc).Item(4) = txtPassword.Text
txtClass.Text = ds.Tables("Users").Rows(inc).Item(5) = txtClass.Text
txtAdmin.Text = ds.Tables("Users").Rows(inc).Item(6) = txtAdmin.Text
txtHWP.Text = ds.Tables("Users").Rows(inc).Item(7) = txtHWP.Text
MessageBox.Show("Data updated")
End Sub
Public Class AdminEditUsers 'this is the whole code
Dim MaxRows As Integer
Dim inc As Integer
Dim con As New OleDb.OleDbConnection 'THE CONNECTION OBJECT
Dim dbProvider As String 'HOLDS THE PROVIDER
Dim dbSource As String 'HOLDS THE DATA SOURCE
Dim MyDocumentsFolder As String 'HOLDS THEDOCUMENTS FOLDER
Dim TheDatabase As String 'HOLDS THE DATABASE NAME
Dim FullDatabasePath As String 'HOLDS THE DATABASE PATH
Dim ds As New DataSet 'HOLDS A DataSet OBJECT
Dim da As OleDb.OleDbDataAdapter 'HOLDS A DataAdapter OBJECT
Dim sql As String 'HOLDS A SQL STRING
Private Sub AdminEditUsers_load(sender As Object, e As EventArgs) Handles Me.Load
'SET UP THE PROVIDER
dbProvider = "PROVIDER=Microsoft.ACE.OLEDB.12.0;"
'SET THE DATABASE AND WHERE THE DATABASE IS
TheDatabase = "\Visual Studio 2015/NEW_database.accdb"
MyDocumentsFolder = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
FullDatabasePath = MyDocumentsFolder & TheDatabase
'SET THE DATA SOURCE
dbSource = "Data Source = " & FullDatabasePath
'SET THE CONNECTION STRING
con.ConnectionString = dbProvider & dbSource
'OPEN THE DATABASE
con.Open()
'STORE THE SQL STRING
sql = "Select * FROM tbl_user"
'PASS THE SQL STRING AND CONNECTION OBJECT TO THE DATA_ADAPTER
da = New OleDb.OleDbDataAdapter(sql, con)
'Fill the dataset with records from the database table
da.Fill(ds, "Users")
'CLOSE THE DATABASE
con.Close()
'Counts how many rows are in the table
MaxRows = ds.Tables("Users").Rows.Count
inc = -1
End Sub
Private Sub NavigateRecords()
txtFirstName.Text = ds.Tables("Users").Rows(inc).Item(1)
txtSurname.Text = ds.Tables("Users").Rows(inc).Item(2)
txtUsername.Text = ds.Tables("Users").Rows(inc).Item(3)
txtPassword.Text = ds.Tables("Users").Rows(inc).Item(4)
txtClass.Text = ds.Tables("Users").Rows(inc).Item(5)
txtAdmin.Text = ds.Tables("Users").Rows(inc).Item(6)
txtHWP.Text = ds.Tables("Users").Rows(inc).Item(7)
End Sub
Private Sub btnNext_Click(sender As Object, e As EventArgs) Handles btnNext.Click
If inc <> MaxRows - 1 Then
inc = inc + 1
NavigateRecords()
Else
MessageBox.Show("No More Rows")
End If
End Sub
Private Sub btnPrevious_Click(sender As Object, e As EventArgs) Handles btnPrevious.Click
If inc > 0 Then
inc = inc - 1
NavigateRecords()
ElseIf inc = -1 Then
MessageBox.Show("No Records Yet")
ElseIf inc = 0 Then
MessageBox.Show("First Record")
End If
End Sub
Private Sub btnLast_Click(sender As Object, e As EventArgs) Handles btnLast.Click
If inc <> MaxRows - 1 Then
inc = MaxRows - 1
NavigateRecords()
End If
End Sub
Private Sub btnFirst_Click(sender As Object, e As EventArgs) Handles btnFirst.Click
If inc <> 0 Then
inc = 0
NavigateRecords()
End If
End Sub
Private Sub btnAddNew_Click(sender As Object, e As EventArgs) Handles btnAddNew.Click
End Sub
Private Sub btnCommit_Click(sender As Object, e As EventArgs) Handles btnCommit.Click
End Sub
Private Sub btnUpdate_Click(sender As Object, e As EventArgs) Handles btnUpdate.Click
txtFirstName.Text = ds.Tables("Users").Rows(inc).Item(1) = txtFirstName.Text
txtSurname.Text = ds.Tables("Users").Rows(inc).Item(2) = txtSurname.Text
txtUsername.Text = ds.Tables("Users").Rows(inc).Item(3) = txtUsername.Text
txtPassword.Text = ds.Tables("Users").Rows(inc).Item(4) = txtPassword.Text
txtClass.Text = ds.Tables("Users").Rows(inc).Item(5) = txtClass.Text
txtAdmin.Text = ds.Tables("Users").Rows(inc).Item(6) = txtAdmin.Text
txtHWP.Text = ds.Tables("Users").Rows(inc).Item(7) = txtHWP.Text
MessageBox.Show("Data updated")
End Sub
Private Sub btnDelete_Click(sender As Object, e As EventArgs) Handles btnDelete.Click
End Sub
Private Sub btnClear_Click(sender As Object, e As EventArgs) Handles btnClear.Click
End Sub
End Class
Where are you actually updating the database?
Read one more paragraph in that tutorial:
Close down your programme, then run it again. Click the Next Record button to move to the first record. It will still be "John Smith". The data you updated has been lost! So here, again, is why:
"Changes are made to the DataSet, and NOT to the Database"
The tutorial shows you how to persist those changes to the database:
da.Update(ds, "AddressBook")
Edit: It would also appear that you're making a mistake on lines like this:
txtFirstName.Text = ds.Tables("Users").Rows(inc).Item(1) = txtFirstName.Text
This may behave differently in different languages. In C# for example, I think that the result of an assignment is the value being assigned, so something like this might work. But in VB there are semantic contextual differences when using the same operator. The assignment operator (=) is also the comparison operator, depending on the context.
So I suspect that this line of code is comparing the latter two items, and assigning the result of the comparison (True or False) to the first item.
Stick with what the tutorial is showing you, just assign the value to the data:
ds.Tables("Users").Rows(inc).Item(1) = txtFirstName.Text
There's no need to also try to assign the value back to the text box where you got the value, since logically that value is already there.

VB displaying elements from multidimensional array in listbox

For some odd reason I am getting an error when I am using my loop to display the elements of my array. I can't seem to understand what it is I am doing or not doing right. This is the code so far. This is not for a class, I am learning myself.
Option Strict On
Option Explicit On
Option Infer Off
Public Class Form1
Private strExams(49, 2) As String
Dim count As Integer = 0
Private Sub btnAdd_Click(sender As Object, e As EventArgs) Handles btnAdd.Click
Dim strStudent As String = txtStudent.Text
Dim strTest As String = txtTest.Text
Dim strScore As String = txtScore.Text
If count <= 49 Then
strExams(count, 0) = strStudent
strExams(count, 1) = strTest
strExams(count, 2) = strScore
count += 1
End If
txtStudent.Text = String.Empty
txtTest.Text = String.Empty
txtScore.Text = String.Empty
txtStudent.Focus()
End Sub
Private Sub btnDisplay_Click(sender As Object, e As EventArgs) Handles btnDisplay.Click
Dim intHighRow As Integer = strExams.GetUpperBound(0)
Dim intHighCol As Integer = strExams.GetUpperBound(1)
Dim intR As Integer
Dim intC As Integer
Do While intC <= intHighCol
intR = 0
Do While intR <= intHighRow
lstMessage.Items.Add(strExams(intR, intC))
intR += 1
Loop
intC += 1
Loop
End Sub
This is the error I am getting when I click my display button.
An unhandled exception of type 'System.ArgumentNullException' occurred in System.Windows.Forms.dll
Additional information: Value cannot be null.
Try this. This makes much more sense to me. The reason you're getting a null error is that you haven't filled everything up in your array and your listbox can't list null items. So a workaround would be to enumerate only items that already have values, thus, just loop until the last value of count.
Private Sub btnDisplay_Click(sender As Object, e As EventArgs) Handles btnDisplay.Click
Dim intR As Integer
lstMessage.Items.Clear()
Do While intR < count
lstMessage.Items.Add(strExams(intR, 0) & " - " & strExams(intR, 1) & " - " & strExams(intR, 2))
intR += 1
Loop
End Sub

Resources