VB.net | Finding duplicates in a multidimensional array - vb.net

I have two forms: Act9.vb and List.vb. The code in both forms is below. I'm using vb.net "4.7.2" in visual studio.
I have been very frustrated with this program for a while now. For some reason the program only checks new clients against the first and second clients already in the list. For example, if the following entries are in the list:
╔═════════╦═════════════╗
║ ClientA ║ 32423223343 ║
╠═════════╬═════════════╣
║ ClientB ║ 23422322343 ║
╠═════════╬═════════════╣
║ ClientC ║ 23423423423 ║
╠═════════╬═════════════╣
║ ClientD ║ 43533453333 ║
╠═════════╩═════════════╣
║ etc... ║
╚═══════════════════════╝
Then if I try to modify ClientA or ClientB (pressing btnModify and then typing "ClientA"/"ClientB" in the inputbox), then it works, but if I try the same with ClientC, D, E, etc. it doesn't. I get this message: "This client doesn't exist. Please try again."
Same thing with adding new clients: it won't let me add ClientA or B twice, but if I try to add Client C more then once it doesn't realize that it's already in the multidimensional array and let's me add it a second time.
If someone knows anything that can help, please share.
Thanks in advance!
Public Class Act9
Public Clients(1, 1) As String
Public size As Integer = 0
Sub Add()
Dim tempClient As String
Dim tempTel As String
tempClient = InputBox("Please enter the clients name :", "Name")
If Duplicate(tempClient) Then
MsgBox("This client already exists")
Else
tempTel = InputBox("Please enter the client's phone number:", "Phone number")
Clients(0, size) = tempClient
Clients(1, size) = tempTel
size += 1
ReDim Preserve Clients(1, size)
End If
End Sub
Function Duplicate(ByVal tempClient As String) As Boolean
Dim output As Boolean = False
For i As Integer = LBound(Clients) To UBound(Clients)
If Clients(0, i) = tempClient Then
output = True
End If
Next
Return output
End Function
Private Sub BtnAdd_Click(sender As Object, e As EventArgs) Handles btnAdd.Click
Add()
End Sub
Private Sub btnShow_Click(sender As Object, e As EventArgs) Handles btnShow.Click
List.ShowDialog()
End Sub
Private Sub btnErase_Click(sender As Object, e As EventArgs) Handles btnErase.Click
ReDim Clients(1, size)
List.lstClients.Items.Clear()
size = 0
End Sub
Private Sub btnModify_Click(sender As Object, e As EventArgs) Handles btnModify.Click
modify()
End Sub
Sub modify(Optional who As String = Nothing)
Dim change As Boolean = False
If who = Nothing Then who = InputBox("Please enter the name of the client you wish to modify:", "Modify")
For i As Integer = LBound(Clients) To UBound(Clients)
If Clients(0, i) = who Then
Clients(0, i) = InputBox("Please enter the new name for the client:", "Name")
Clients(1, i) = InputBox("Please enter the new phone number for the client", "Phone number")
change = True
Exit For
End If
Next
If change = False Then MsgBox("This client doesn't exist. Please try again.")
End Sub
End Class
Public Class List
Private Sub List_Load(sender As Object, e As EventArgs) Handles Me.Load
lstClients.Items.Clear()
For i As Integer = 0 To Act9.size - 1
lstClients.Items.Add(Act9.Clients(0, i) & vbTab & Act9.Clients(1, i))
Next
End Sub
End Class

#Craig Told me to use breakpoints which are the perfect tools for this. I'm very grateful for the advice.
Here is how I ended up getting it to work properly:
I replaced LBound and Ubound with my variable "size" (which was already taking care of counting the size of my multidimensional array).
The For loop in "Duplicate" becomes:
For i As Integer = 0 To size
If Clients(0, i) = tempClient Then
output = True
End If
Next
The one in "Modify becomes:
For i As Integer = 0 To size
If Clients(0, i) = who Then
Clients(0, i) = InputBox("Please enter the new name for the client:", "Name")
Clients(1, i) = InputBox("Please enter the new phone number for the client", "Phone number")
change = True
Exit For
End If
Next

The reason why your original code didn't work out is because you LBound/UBound on the first dimension but your array extends on the second dimension. The first dimension is only ever 0 to 1 so you only ever checked the second dimension indexes 0 and 1 (the first two items) for the name:
For i As Integer = LBound(Clients) To UBound(Clients)
If you use
LBound(Clients, 2) to UBound(Clients, 2)
It will get the upper limit of the second dimension rather than the first. UBound uses 1-based indexing whereas VB uses 0 based. If you want the same thing in 0 based you can use
Array.GetUpperBound(Clients, 1)
to find the limit of the second dimension
Other tips:
your modify method makes the same bounding mistake
if this were programming 201 you'd probably be using a List(Of Client), Client being a class having a pair of string properties for name and tel, and an overridden equals method that compares the name of an incoming Client, so that list.Contains can be used to prevent duplicates. Eventually you'd probably override GetHashCode too and use a HashSet(Of Client). And this whole thing would actually be a lot easier. Multidimensional arrays are usually a poor storage solution for.. well.. everything
your size variable is public; it should have a capital s
your modify method is a method; it should have a capital M. All methods in .net have capital initial letters
maybe btnErase should set the size before it redims
your duplicate method checks every item in the array. It carries on checking even if it already found a duplicate item. You can skip the part where you create a Boolean and just straight Return True inside the If; your keys are always in the last place you look because you stop looking when you find them :)
perhaps if you implement a FindIndex method that takes a name and returns the index of where that person is, or -1 if it didn't find them then you can use it for both IsDuplicate (call findindex and return true if the result is greater than -1) and for Modify (find the index of the person and change them or put a message Not Found if -1 comes bac). This means you can have just one method that searches the array and you use it twice. It means you Don't Repeat Yourself - a software engineering principle we try to stick to. At the moment your duplicate and modify methods both have the same loop (with the same bug)

Related

How to use Nested Loop in Visual Basic for all unrepeated combinations of characters?

I am trying to get the combinations of all possible unrepeated character sets from the user input.
As I am just beginning to learn the programming, it is obvious that I don't properly understand how those nested loops work.
Here is my code:
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
ListBox1.Items.Clear()
Dim c1 As String = TextBox1.Text
Dim i, j As Integer
Dim str As String()
Dim k As Integer = 0
For i = 0 To c1.Length - 1
For j = 0 To i
ListBox1.Items.Add(c1(i) & c1(j))
Next
Next
End Sub
End Class
As you can see in the picture attached, I cannot get the rest. How can I get the character pairs I put in the red box on notepad?
Can someone help me, please.enter image description here
You had the right idea. However, expand your logic so that for every letter of the outer loop you spin through every letter again. And if you don't want repeated letter pairs, add an If statement:
For i = 0 To c1.Length - 1
For j = 0 To c1.Length - 1
If i <> j Then ListBox1.Items.Add(c1(i) & c1(j))
Next
Next

What method would make this code more efficient or proper?

I have a program that collects information based on the radio buttons that are checked, as well as a checkbox.
Private Sub calculateBtn_Click(sender As Object, e As EventArgs) Handles calculateBtn.Click
Dim TypeCost As Integer
Dim ColorCost As Integer
Dim Foldable As Integer
If standardRbtn.Checked() Then
TypeCost = 99
End If
If deluxRbtn.Checked() Then
TypeCost = 129
End If
If premiumRbtn.Checked() Then
TypeCost = 179
End If
If blueRbtn.Checked() Then
ColorCost = 0
End If
If redRbtn.Checked() Then
ColorCost = 10
End If
If pinkRbtn.Checked() Then
ColorCost = 15
End If
If foldableCheckBox.Checked() Then
Foldable = 25
Else
Foldable = 0
End If
Dim Price As String = TypeCost + ColorCost + Foldable
priceTextBox.Text() = "$" & Price
End Sub
I have a strong feeling that this code can be simplified, but I just can't seem to think of what it is. My friend suggested Enumerations and Arrays, but I don't think those would work. Would they?
I have been searching around for a question similar to this for a while now.
I would also like to point out that the type radio buttons and the color radio buttons are in separate group boxes, so they function separately. Making it impossible for more than one type or color to be selected at the same time.
I have uptade the code to:
If standardRbtn.Checked() Then
TypeCost = 99
ElseIf deluxRbtn.Checked() Then
TypeCost = 129
ElseIf premiumRbtn.Checked() Then
TypeCost = 179
End If
If blueRbtn.Checked() Then
ColorCost = 0
ElseIf redRbtn.Checked() Then
ColorCost = 10
ElseIf pinkRbtn.Checked() Then
ColorCost = 15
End If
If foldableCheckBox.Checked() Then
Foldable = 25
Else
Foldable = 0
End If
I knew there was something extremely simply I would be able to do to sort of get rid of some of the repetitiveness. Thank you, phatfingers.
If there's any other ideas anyone would like to throw out, I would love to hear them. But this solution is good enough for me.
I simply went from using a bunch of if statements to "ElseIf". The updated code is in the original thread. :) - Thank you to phatfingers for the idea.
You could use a dropdown, which would probably be the lowest effort solution and allow you to dynamically add new options without rewriting anything.
You can then just fetch the value of the selected item.
https://forums.asp.net/t/988528.aspx?Dynamically+adding+items+in+DropDownList
So something like:
Private Sub OnFormLoad() //I forgot the exact name of the load event of the form and what it looks like
typeDropDown.Items.Add(New ListItem("Standard", "99"))
typeDropDown.Items.Add(New ListItem("Premium", "129"))
typeDropDown.Items.Add(New ListItem("Deluxe", "179"))
colorDropDown.Items.Add(New ListItem("Blue", "0"))
colorDropDown.Items.Add(New ListItem("Red", "10"))
colorDropDown.Items.Add(New ListItem("Pink", "15"))
End Sub
Private Sub calculateBtn_Click(sender As Object, e As EventArgs) Handles calculateBtn.Click
Dim Price as String = typeDropDown.SelectedValue + _
colorDropDown.SelectedValue + _
iif(foldableCheckBox.Checked(), 25, 0)
priceTextBox.Text() = "$" & Price
End Sub

What is wrong with my subroutines?

So I've been working on this project for a couple of weeks, as I self teach. I've hit a wall, and the community here has been so helpful I come again with a problem.
Basically, I have an input box where a user inputs a name. The name is then displayed in a listbox. The name is also put into an XML table if it is not there already.
There is a button near the list box that allows the user to remove names from the list box. This amends the XML, not removing the name from the table, but adding an end time to that name's child EndTime.
If the user then adds the same name to the input box, the XML gets appended to add another StartTime rather than create a new element.
All of this functions well enough (My code is probably clunky, but it's been working so far.) The problem comes when I try to validate the text box before passing everything through to XML. What I am trying to accomplish is that if the name exists in the listbox on the form (i.e hasn't been deleted by the user) then nothing happens to the XML, the input box is cleared. This is to prevent false timestamps due to a user accidentally typing the same name twice.
Anyhow, I hope that makes sense, I'm tired as hell. The code I've got is as follows:
Private Sub Button1_Click_2(sender As System.Object, e As System.EventArgs) Handles addPlayerButton.Click
playerTypeCheck()
addPlayerXML()
clearAddBox()
End Sub
Private Sub playerTypeCheck()
If playerTypeCBox.SelectedIndex = 0 Then
addMiner()
ElseIf playerTypeCBox.SelectedIndex = 1 Then
addHauler()
ElseIf playerTypeCBox.SelectedIndex = 2 Then
addForeman()
End If
End Sub
Private Sub addMiner()
If minerAddBox.Text = String.Empty Then
Return
End If
If minerListBox.Items.Contains(UCase(minerAddBox.Text)) = True Then
Return
Else : minerListBox.Items.Add(UCase(minerAddBox.Text))
End If
If ComboBox1.Items.Contains(UCase(minerAddBox.Text)) = True Then
Return
Else : ComboBox1.Items.Add(UCase(minerAddBox.Text))
End If
End Sub
Private Sub addPlayerXML()
If System.IO.File.Exists("Miners.xml") Then
Dim xmlSearch As New XmlDocument()
xmlSearch.Load("Miners.xml")
Dim nod As XmlNode = xmlSearch.DocumentElement()
If minerAddBox.Text = "" Then
Return
Else
If playerTypeCBox.SelectedIndex = 0 Then
nod = xmlSearch.SelectSingleNode("/Mining_Op/Miners/Miner[#Name='" + UCase(minerAddBox.Text) + "']")
ElseIf playerTypeCBox.SelectedIndex = 1 Then
nod = xmlSearch.SelectSingleNode("/Mining_Op/Haulers/Hauler[#Name='" + UCase(minerAddBox.Text) + "']")
ElseIf playerTypeCBox.SelectedIndex = 2 Then
nod = xmlSearch.SelectSingleNode("/Mining_Op/Foremen/Foreman[#Name='" + UCase(minerAddBox.Text) + "']")
End If
If nod IsNot Nothing Then
nodeValidatedXML()
Else
Dim docFrag As XmlDocumentFragment = xmlSearch.CreateDocumentFragment()
Dim cr As String = Environment.NewLine
Dim newPlayer As String = ""
Dim nod2 As XmlNode = xmlSearch.SelectSingleNode("/Mining_Op/Miners")
If playerTypeCBox.SelectedIndex = 0 Then
newMinerXML()
ElseIf playerTypeCBox.SelectedIndex = 1 Then
newHaulerXML()
ElseIf playerTypeCBox.SelectedIndex = 2 Then
newForemanXML()
End If
End If
End If
Else
newXML()
End If
End Sub
Private Sub nodeValidatedXML()
If playerTypeCBox.SelectedIndex = 0 Then
minerValidatedXML()
ElseIf playerTypeCBox.SelectedIndex = 1 Then
haulerValidatedXML()
ElseIf playerTypeCBox.SelectedIndex = 2 Then
foremanValidatedXML()
End If
End Sub
Private Sub minerValidatedXML()
If minerListBox.Items.Contains(UCase(minerAddBox.Text)) = False Then
appendMinerTimeXML()
End If
End Sub
Private Sub appendMinerTimeXML()
Dim xmlSearch As New XmlDocument()
xmlSearch.Load("Miners.xml")
Dim docFrag As XmlDocumentFragment = xmlSearch.CreateDocumentFragment()
Dim cr As String = Environment.NewLine
Dim newStartTime As String = Now & ", "
Dim nod2 As XmlNode = xmlSearch.SelectSingleNode("/Mining_Op/Miners/Miner[#Name='" & UCase(minerAddBox.Text) & "']/StartTime")
docFrag.InnerXml = newStartTime
nod2.AppendChild(docFrag)
xmlSearch.Save("Miners.xml")
End Sub
And lastly, the clearAddBox() subroutine
Private Sub clearAddBox()
minerAddBox.Text = ""
End Sub
So, I should point out, that if I rewrite the nodeValidated() Subroutine to something like:
Private Sub nodeValidatedXML()
If playerTypeCBox.SelectedIndex = 0 Then
appendMinerTimeXML()
ElseIf playerTypeCBox.SelectedIndex = 1 Then
appendHaulerTimeXML()
ElseIf playerTypeCBox.SelectedIndex = 2 Then
appendForemanTimeXML()
End If
End Sub
then all of the XML works, except it adds timestamps on names that already exist in the list, which is what i'm trying to avoid. So if I haven't completely pissed you off yet, what is it about the minerValidated() subroutine that is failing to call appendMinerTimeXML()? I feel the problem is either in the minerValidated() sub, or perhaps clearAddBox() is somehow firing and I'm missing it? Thanks for taking the time to slog through this.
Edit: Clarification. The code as I have it right now is failing to append the XML at all. Everything writes fine the first time, but when I remove a name from the list and then re-add, no timestamp is added to the XML.
You need to prevent the user accidentally typing the name twice.(Not sure if you mean adding it twice)
For this I believe you need to clear the minerAddBox.Text in your addminer() if this line is true.
minerListBox.Items.Contains(UCase(minerAddBox.Text)) = True
minerAddBox.Text = ""
Return
Now it will return back to your addplayerXML which will Return to your clearbox(), since you have this in your addplayerXML()
If minerAddBox.Text = "" Then
Return
Now you get to your clearbox() (Which is not really needed now since you cleared the minerAddBox.Text already)
when I remove a name from the list and then re-add, no timestamp is added to the XML.
your minerValidatedXML() is true, because you are not clearing the textbox when you re-add a name to the list box. Or you may need to remove the existing listbox item if it is the same as the textbox
If minerListBox.Items.Contains(UCase(minerAddBox.Text)) = True Then
minerListBox.Items.remove(UCase(minerAddBox.Text))

Collection was modified; enumeration operation may not execute. VB thearding

Here is my code,
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
For Each kthread As Thread In _threads
If kthread.Name = "123" Then
_threads.Remove(kthread)
kthread.Abort()
killedthreads += 1 'a integer
End If
Next
End Sub
I added the killedthreads integer at last as a check, vb executes the whole function good but at the last line it always throw the error said in title.
Not sure why, if killedthreads += 1 is not there then the error goes to kthread.Abort()
I had the same problem with C# with a different app earlier this year.
Edit,
Public Sub KillThread(kThread As Thread)
For i As Integer = (_threads.Count - 1) To 0 Step -1
If _threads.Item(i).Name = kThread.Name Then
_threads.Item(i).Abort()
_threads.RemoveAt(i)
End If
Next
End Sub
I did this code as Eminem said it. This gets in kThread from the running threads if something is not good or it has finished all its functions. But my problem is that, only the first thread that sends it gets abort and removed from list, others seem to get stuck once the first thread is aborted.
I create threads using,
Public Sub multiThreader(int As Integer, link As String)
Dim tCount As Integer = _threads.Count
If tCount >= Form1.ListView1.Items.Count Then
Else
Dim dy As Integer = DateTime.Now.Day
Dim mo As Integer = DateTime.Now.Month
Dim fileNum As String = dy.ToString() + "-" + mo.ToString() + "_" + int.ToString
botThread = New Thread(Sub() MainThread(fileNum, link, botThread, int.ToString()))
botThread.IsBackground = True
botThread.Name = String.Format("AutoBotThread{0}", fileNum)
_threads.Add(botThread)
botThread.Start()
End If
End Sub
and _threads is publicly, Public _threads As New List(Of Thread)
MainThread is a Public Sub which runs functions and gets return and send KillThread under certain conditions.
The problem is that you remove an item from an enumeration, before you finished iterating through it.
It's like trying to iterate from 0 to list.count, when the count changes from an iteration to another. As Bjørn-Roger Kringsjå said, you should do something like this:
For i As Integer = (_threads.count - 1) to 0 Step -1
If _threads.Item(i).Name = "123" Then
_threads.Item(i).Abort
_threads.RemoveAt(i)
killedthreads += 1 'a integer
End If
Next
By using Step -1 you make sure that an Index was out of range error will not occur, and make sure that your operations are fitted, and execute on the right order/item.

Binary Search or Insertion Sort with list view [Visual Basic .net]

Recently when creating a program for my client as part of my computing project in visual basic .net I've came across a problem, which looks like following; In order to receive additional marks for my program I must take an advantage of either Binary Search or Insertion Sort subroutine declared recursively, so far the only place I can use it on is my View form which displays all reports generated by program but the problem with this is since I'm using MS Access to store my data all of the data is downloaded and placed in listview in load part of form. So the only way I can use it is by running it on listview which is a major problem for me due to the fact that I'm not very experienced in vb.
For binary search I have tried downloading all of the items in specified by user column into an array but that's the bit I was struggling on the most because I'm unable to download all items from only one column into an array. Also instead of searching every single column user specifies in my form in which column item is located (For example "19/02/2013" In Column "Date"), In my opinion if I manage to download every single entry in specified column into an array it should allow me to run binary search later on therefore completing the algorithm. Here's what I've got so far.
Sub BinarySearch(ByVal Key As String, ByVal lowindex As String, ByVal highindex As String, ByVal temp() As String)
Dim midpoint As Integer
If lowindex > highindex Then
MsgBox("Search Failed")
Else
midpoint = (highindex + lowindex) / 2
If temp(midpoint) = Key Then
MsgBox("found at location " & midpoint)
ElseIf Key < temp(midpoint) Then
Call BinarySearch(Key, lowindex, midpoint, temp)
ElseIf Key > temp(midpoint) Then
Call BinarySearch(Key, midpoint, highindex, temp)
End If
End If
End Sub
Private Sub btnSearch_Click(sender As System.Object, e As System.EventArgs) Handles btnSearch.Click
Dim Key As String = txtSearch.Text
Dim TargetColumn As String = Me.lstOutput.Columns(cmbColumns.Text).Index
Dim lowindex As Integer = 0
Dim highindex As Integer = lstOutput.Items.Count - 1
'Somehow all of the items in Target column must be placed in temp array
Dim temp(Me.lstOutput.Items.Count - 1) As String
' BinarySearch(Key, lowindex, highindex, temp)
End Sub
For Insertion sort i don't even have a clue how to start, and the thing is that I have to use my own subroutine instead of calling system libraries which will do it for me.
Code which I have to use looks like following:
Private Sub InsertionSort()
Dim First As Integer = 1
Dim Last As Integer = Me.lstOutput.
Dim CurrentPtr, CurrentValue, Ptr As Integer
For CurrentPtr = First + 1 To Last
CurrentValue = A(CurrentPtr)
Ptr = CurrentPtr - 1
While A(Ptr) > CurrentValue And Ptr > 0
A(Ptr + 1) = A(Ptr)
Ptr -= 1
End While
A(Ptr + 1) = CurrentValue
Next
Timer1.Enabled = False
lblTime.Text = tick.ToString
End Sub
Any ideas on how to implement this code will be very appreciated, and please keep in my mind that I'm not very experienced in this language
Perhaps this might give you a place to begin. If you already have a ListView with "stuff" in it you could add a button to the form with the following code to copy the Text property for each item into an array:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim myArray(Me.ListView1.Items.Count - 1) As String
Dim i As Integer
' load array
For i = 0 To Me.ListView1.Items.Count - 1
myArray(i) = Me.ListView1.Items(i).Text
Next
' show the results
Dim s As String = ""
For i = 0 To UBound(myArray)
s &= String.Format("myArray({0}): {1}", i, myArray(i)) & vbCrLf
Next
MsgBox(s, MsgBoxStyle.Information, "myArray Contents")
' now go ahead and manipulate the array as needed
' ...
End Sub