Compare the values of two listboxes and add the non-equivalent values to a third listbox - vb.net

My knowledge of programming is not too extensive but I have just finished my second year of higher education in computer engineering and have taken a few low level programming courses.
In Visual Basic, I am having trouble comparing the values of two ListBox controls and putting the values that aren't the same into another ListBox.
I need to compare the items of ListBox2 to the items of ListBox1 and if there are any items in ListBox2 that are not in ListBox1, add them to ListBox3. I do not need to find the items in ListBox1 that are not in ListBox2. I cannot use a loop to compare their values based on index because these lists are of names which will be constantly added to and removed from. I also cannot sort these ListBoxes.
There was an example for C# that I found here that used LINQ (I don't really know what that is) to compare the lists and then add the result to a TextBox control. However, I need to know how to add them to a ListBox and not a TextBox.
[EDIT] The example that I have tried is this:
Dim result As List(Of String) = (From s1 As String In Me.ListBox1.Items Where Not Me.ListBox2.Items.Contains(s1) Select s1).ToList()
Me.TextBox1.Text = String.Join(Environment.NewLine, result)

Dim one As ListBox = New ListBox()
Dim two As ListBox = New ListBox()
Dim three As ListBox = New ListBox()
Dim unique As Boolean = True
For i As Integer = 0 To one.Items.Count
For j As Integer = 0 To two.Items.Count
If (one.Text = two.Text) Then
unique = False
Else
two.SelectedIndex = j
End If
Next
If (unique) Then
three.Items.Add(one.Text)
Else
one.SelectedIndex = i
unique = True
End If
Next
I believe this may be what you're looking for. What it does is compares each value in Listbox one to all values in Listbox two and if a value is seen to be a duplicate the Boolean flag unique is switched to false and the item is not added to Listbox three.

I think i found the solution:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
ListBox3.Items.Clear()
Dim result As List(Of String) = (From s1 As String In Me.ListBox2.Items Where Not Me.ListBox1.Items.Contains(s1) Select s1).ToList()
For Each l In result
ListBox3.Items.Add(l)
Next
End Sub
or
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim result As List(Of String) = (From s1 As String In Me.ListBox2.Items Where Not Me.ListBox1.Items.Contains(s1) Select s1).ToList()
For Each l In result
If Not ListBox3.Items.Contains(l) Then
ListBox3.Items.Add(l)
End If
Next
End Sub
Try which works best for you :)

Related

How to get item text from CheckedListBox to ListBox without repeating the before text? VB.net

I have a CheckedListBox of 10 names A to J (it's a string but here I'm just using abc), and I want to make it so that every time a user check something, the text will be shown in the listbox simultaneously. I have tried this:
For i = 0 To chklistbxDrugAvailableList.Items.Count - 1
Dim drugs As String = CType(chklistbxDrugAvailableList.Items(i), String)
If chklistbxDrugAvailableList.GetItemChecked(i) Then
listbxYourOrder.Items.Add(drugs)
End If
'drugs = nothing
Next
But when I check A,B,C the text in the Listbox got repeated like so:
A
A
B
A
B
C
I don't know why this is happening. I didn't declare drugs as an array. Even when I used the drugs = nothing, it still give repeated values.
What should I do? Sorry if this is a noob question.
Here is how I would do the whole thing:
Private Sub CheckedListBox1_ItemCheck(sender As Object, e As ItemCheckEventArgs) Handles CheckedListBox1.ItemCheck
'Clear the current ListBox contents.
ListBox1.Items.Clear()
'Get the indexes of the currently checked items.
Dim checkedIndices = CheckedListBox1.CheckedIndices.Cast(Of Integer)()
'Add the current index to the list if the item is being checked, otherwise remove it.
checkedIndices = If(e.NewValue = CheckState.Checked,
checkedIndices.Append(e.Index),
checkedIndices.Except({e.Index}))
'Get the checked items in order and add them to the ListBox.
ListBox1.Items.AddRange(checkedIndices.OrderBy(Function(n) n).
Select(Function(i) CheckedListBox1.Items(i)).
ToArray())
End Sub
or like this:
Private Sub CheckedListBox1_ItemCheck(sender As Object, e As ItemCheckEventArgs) Handles CheckedListBox1.ItemCheck
'Get the indexes of the currently checked items.
Dim checkedIndices = CheckedListBox1.CheckedIndices.Cast(Of Integer)()
'Add the current index to the list if the item is being checked, otherwise remove it.
checkedIndices = If(e.NewValue = CheckState.Checked,
checkedIndices.Append(e.Index),
checkedIndices.Except({e.Index}))
'Get the checked items in order and add them to the ListBox.
ListBox1.DataSource = checkedIndices.OrderBy(Function(n) n).
Select(Function(i) CheckedListBox1.Items(i)).
ToArray()
End Sub
The difference is that, because the second option uses data-binding, the first item in the ListBox will be selected by default.
The reason that it needs to be a bit verbose is that the ItemCheck event is raised before the item is checked or unchecked. For that reason, we need to get the currently checked items first and then either add or remove the current item, depending on whether the current item is being checked or unchecked.
EDIT:
Here's an option that doesn't require clearing the ListBox:
Private Sub CheckedListBox1_ItemCheck(sender As Object, e As ItemCheckEventArgs) Handles CheckedListBox1.ItemCheck
Dim item = CheckedListBox1.Items(e.Index)
If e.NewValue = CheckState.Checked Then
ListBox1.Items.Add(item)
Else
ListBox1.Items.Remove(item)
End If
End Sub
The issue with that is that the items will appear in the ListBox in the order you checked them, rather than the order they appear in the CheckedListBox. The other options keep the items in the same order in both lists.
If I understand your question I would this:
lstbxYourOrder.Items.Clear()
For Each l As String In chklistbxDrugAvailableList.CheckedItems
listbxYourOrder.Items.Add(l)
Next

Select random person from text file and change corresponding values

I have a form with a button and a label. I also have a text file with the following contents:
Bob:Available:None:0
Jack:Available:None:0
Harry:Available:None:0
Becky:Unavailable:Injured:8
Michael:Available:None:0
Steve:Available:None:0
Annie:Unavailable:Injured:12
Riley:Available:None:0
The values in the text file are:
person-name:available-or-unavailable:sick-or-injured:months-they-will-be-unavailable
What I would like to do is to have the user click the button and a random (available) person will be selected from the text file. The label's text will then say:
personname & " has gotten injured and will be unavailable for 10 months."
I would then like to overwrite the text file with the corresponding values for that particular person. For example that person's second value will now be "Unavailable", the third value will be "Injured" and the fourth value will be 10.
I hope this makes sense.
I don't have any code, as I literally have no idea how to do this. Any help would be much appreciated!
Explanations and code in line.
Private r As New Random
Private RandomIndex As Integer
Private dt As New DataTable
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
AddColumnsToDataTable()
FillDataTable()
End Sub
Private Sub AddColumnsToDataTable()
'Need to prepare the table to receive the data
dt.Columns.Add("Name")
dt.Columns.Add("Available")
dt.Columns.Add("Injury")
dt.Columns.Add("Months")
End Sub
Private Sub FillDataTable()
'ReadAllLines returns an array of lines in the text file
Dim lines = File.ReadAllLines("workers.txt")
'Loop through each line in the lines array
For Each line As String In lines
'.Split returns an array based on splitting the line
'by the colon. The c following ":" tells the compiler
'that this is a Char which the split function requires.
Dim items = line.Split(":"c)
'We can add a row to the data table all at once by
'passing in an array of objects.
'This consists of the elements of the items array
dt.Rows.Add(New Object() {items(0), items(1), items(2), items(3)})
Next
'Now we have an in memory DataTable that contains all the data from the text file.
End Sub
Private Function GetRandomWorker() As String
'A list of all the row indexes that are available
Dim AvailableList As New List(Of Integer)
For i As Integer = 0 To dt.Rows.Count - 1
'Loop through all the data in the date table row by row
If dt.Rows(i)("Available").ToString = "Available" Then
'Add only the row indexes that are Available
AvailableList.Add(i)
End If
Next
'Get a random index to use on the list of row indexes in IndexList
If AvailableList.Count = 0 Then
'No more workers left that are Available
Return ""
End If
'Get a random number to use as an index for the available list
Dim IndexForList = r.Next(AvailableList.Count)
'Selects a row index based on the random index in the list of Available
RandomIndex = AvailableList(IndexForList)
'Now use the index to get information from the row in the data table
Dim strName = dt.Rows(RandomIndex)("Name").ToString
Return strName
End Function
Private Sub SaveDataTable()
'Resave the whole file if this was a real app you would use a database
Dim sb As New StringBuilder
'A string builder keeps the code from creating lots of new strings
'Strings are immutable (can't be changed) so every time you think you are
'changing a string, you are actually creating a new one.
'The string builder is mutable (changable)
For Each row As DataRow In dt.Rows
'The ItemsArray returns an array of objects containing all the
'values in each column of the data table.
Dim rowValues = row.ItemArray
'This is a bit of Linq magic that turns the values into strings
Dim strRowValues = From s In rowValues
Select DirectCast(s, String)
'Now that we have strings we can use the String.Join with the colon
'to get the format of the text file
sb.AppendLine(String.Join(":", strRowValues))
Next
'Finally we change the StringBuilder to a real String
'The workers.txt is stored in the Bin\Debug directory so it is current directory
'no additional path required
File.WriteAllText("workers.txt", sb.ToString)
End Sub
Private Sub Form1_FormClosing(sender As Object, e As FormClosingEventArgs) Handles MyBase.FormClosing
SaveDataTable()
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim WorkerName As String = GetRandomWorker()
If WorkerName = "" Then
MessageBox.Show("There are no available workers")
Return
End If
Label1.Text = $"{WorkerName} has gotten injured and will be unavailable for 10 months."
dt.Rows(RandomIndex)("Available") = "Unavailable"
dt.Rows(RandomIndex)("Injury") = "Injured"
dt.Rows(RandomIndex)("Months") = "10"
End Sub

VB.NET Random unique generator

I'l trying to generate a unique random number generator with the snippet of code from below, but it's not working. The IF section is suppose to test if it's the first random number generated, if it is, it's suppose to add the first random number to the ArrayList, if it's not the first random number, it's supposed to check if the random number is already in the ArrayList and if it's in the ArrayList it's suppose to MsgBox and generate a new unique random number that is not already in the ArrayList and add it to the ArrayList, but it's not doing any of those. Any help would be greatly appreciated.
Public Class Form1
Dim r As New Random
Dim dLowestVal As Integer = 1
Dim dHighestVal As Integer = 26
Dim dItemAmount As Integer = 1
Dim RollCheck As New HashSet(Of Integer)
Private Sub btnExit_Click(sender As Object, e As EventArgs) Handles btnExit.Click
End
End Sub
Private Sub btnRollDice_Click(sender As Object, e As EventArgs) Handles btnRollDice.Click
lblRandomNo.Text = r.Next(dLowestVal, dHighestVal)
lblItemAmount.Text = dItemAmount
If dItemAmount = 1 Then
RollCheck.Add(Val(lblRandomNo.Text))
ElseIf (RollCheck.Contains(Val(lblRandomNo.Text))) Then
MsgBox("Already Exists")
lblRandomNo.Text = r.Next(dLowestVal, dHighestVal)
RollCheck.Add(Val(lblRandomNo.Text))
End If
dItemAmount = dItemAmount + 1
Thanks in advance.
You could replace your whole method with this simple one
' This is globally declared at the top of your form
Dim values As New List(Of Integer)
' This is called when you construct your form
' It will store consecutive integers from 1 to 25 (25 elements)
values = Enumerable.Range(1, 25).ToList()
This is the method that extract an integer from your values that is not already used
Private Sub Roll()
' Get an index in the values list
Dim v = r.Next(0, values.Count)
' insert the value at that index to your RollCheck HashSet
RollCheck.Add(values(v))
' Remove the found value from the values list, so the next call
' cannot retrieve it again.
values.Remove(values(v))
End Sub
And you can call it from the previous event handler in this way
Private Sub btnRollDice_Click(sender As Object, e As EventArgs) Handles btnRollDice.Click
if values.Count = 0 Then
MessageBox("No more roll available")
else
Roll()
End Sub
End Sub
The point of the HashSet is that since it doesn't allow duplicates you can just check the return value of Add() to determine whether the number was successfully inserted or if it already exists in the list.
If you want to keep trying until it succeeds all you have to do is wrap it in a loop:
If dHighestVal - dLowestVal >= RollCheck.Count Then
'If the above check passes all unique values are MOST LIKELY already in the list. Exit to avoid infinite loop.
MessageBox.Show("List is full!")
Return 'Do not continue.
End If
Dim Num As Integer = r.Next(dLowestVal, dHighestVal)
'Iterate until a unique number was generated.
While Not RollCheck.Add(Num)
MessageBox.Show("Already exists!")
Num = r.Next(dLowestVal, dHighestVal)
End While
lblRandomNo.Text = Num
An alternative way of writing the loop is: While RollCheck.Add(Num) = False.

Copy values of cells from a DataGridView column to an ArrayList

I am using a DataGridView with an ArrayList. When a user clicks a button, I want the values of the first column (there will be 4 columns total, each having its own ArrayList) of the DataGridView to be written to an ArrayList. I am using an ArrayList because the number of rows in the Datagridview can vary, so the array size cannot be static. The code that I have written, actually searched and got help online with is "almost" working. It will write the values of the first column to the arraylist, but I have to click on the button twice. It will only update the ArrayList on the second click of my button. What needs to change with my code? Thanks from a newbie!
Private Sub btnPrintArray_Click(sender As Object, e As EventArgs) Handles btnPrintArray.Click
Dim message = String.Join(Environment.NewLine, lftMtrAccelRates.ToArray())
lftMtrAccelRates.Clear() 'clears ArrayList
rchTxtBox.Clear() 'Clears rich text box that has array element values in it
For Each d In LftMtr_Data_Grid.Rows.Cast(Of DataGridViewRow)()
Dim num As Integer
If Int32.TryParse(d.Cells(0).Value, num) Then
lftMtrAccelRates.Add(num)
End If
Next
rchTxtBox.Text = message
End Sub`
One possibility:
Private values As New List(Of Integer)
Private Sub btnPrintArray_Click(sender As Object, e As EventArgs) Handles btnPrintArray.Click
values.Clear()
Dim num As Integer
For Each d As DataGridViewRow In LftMtr_Data_Grid.Rows
If Int32.TryParse(d.Cells(0).Value, num) Then
values.Add(num)
End If
Next
rchTxtBox.Lines = values.ConvertAll(Function(x) x.ToString).ToArray
End Sub

Delete line of structure array and update it in tab vb.net

So I have a listbox, filled with informations from a structure tab as follows :
Private Sub Modifier_Load(sender As Object, e As EventArgs) Handles MyBase.Load
For i As Integer = 0 To frmConnecter.TabPolyFlix.Length - 1
ListBox1.Items.Add(frmConnecter.TabPolyFlix(i).strTitre)
Next
End Sub
And I want the user to choose to delete the TabPolyFlix(ListBox1.SelectedIndex) and it has to get updated in the original Tab and thus in the Listbox
P.S I tried this but it only updates it in the listbox, not in the original tab
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
Dim Temp As New List(Of ListViewItem)
For i As Integer = 0 To ListBox1.Items.Count - 1
If ListBox1.SelectedIndices.Contains(i) = False Then
Temp.Add(ListBox1.Items(i))
End If
Next
ListBox1.Items.Clear()
For i As Integer = 0 To Temp.Count - 1
ListBox1.Items.Add(Temp(i))
Next i
End Sub
Arrays have a fixed size. Better use a List(Of ListViewItem) for TabPolyFlix. Then assign the List directly to the DataSource of the listbox:
'Fill the listbox
ListBox1.DisplayMember = "strTitre" 'You can also set this in the property grid.
ListBox1.DataSource = frmConnecter.TabPolyFlix
You can also override the ToString method of ListViewItem in order to display anything you want in the listbox and keep ListBox1.DisplayMember empty.
Now you can directly delete the item in the list:
frmConnecter.TabPolyFlix.Remove(ListBox1.SelectedItem)
or
frmConnecter.TabPolyFlix.RemoveAt(ListBox1.SelectedIndex)
or if you want to delete several items at once
For Each i As Integer In ListBox1.SelectedIndices.Cast(Of Integer)()
frmConnecter.TabPolyFlix.Remove(ListBox1.Items(i))
Next
and re-display the list:
ListBox1.DataSource = Nothing
ListBox1.DataSource = frmConnecter.TabPolyFlix
The moral of the story is: don't use controls (the ListBox in this case) as your primary data structure. Use it only for display and user interaction. Perform the logic (the so called business logic) on display-independent data structures and objects (so called business objects) and when finished, display the result.