Check if first 3 items in listview1 matches one of listview2's items - vb.net

I'm working on a project where the program gets items from a table and puts it in a listview. Now I want to check if the top 3 items matches the items in another listview i have set up and return a message whether or not listview1 contains any items from listview2. I can do this for the whole listview1 but I want to check the top 3 only.
For Each li As ListViewItem In ListView2.Items
Dim liToFind As ListViewItem = ListView1.FindItemWithText(li.Text)
If Not IsNothing(liToFind) Then
Using New Centered_MessageBox(Me)
MessageBox.Show(li.Text & " has released a new episode!", "New release", MessageBoxButtons.OK, MessageBoxIcon.Information)
End Using
End If
Next
This is the code for what I have so far, im checking the text of the items in listview2 to see if it matches any of the items in listview1, can't figure out how to do it with the top 3 only though.
Help would be greatly apriciated!

Here is an example - obviously you can be cleverer here .
Dim checkrows As Integer = 3
Dim numFound As Integer
For row As Integer = 0 To Math.Min(checkrows - 1, ListView1.Items.Count - 1)
Dim text As String = ListView1.Items(row).Text
Dim found As Boolean
For Each item2 As ListViewItem In ListView2.Items
If text.Contains(item2.Text) Then
found = True
Exit For
End If
Next
If found Then numFound += 1
Next
If numFound > 0 Then MessageBox.Show("At least one of the first " & checkrows.ToString & " rows in ListView1 matches a row in ListView2")
If numFound = checkrows Then MessageBox.Show("The first " & checkrows.ToString & " rows in ListView1 match a row in ListView2")

This worked for me, thanks AltF4 but yours didn't really work out for me. Ty for putting your time into this anyway <3
Dim checkrows As Integer = 3
Dim numFound As Integer
For row As Integer = 0 To Math.Min(checkrows - 1, ListView1.Items.Count - 1)
Dim text As String = ListView1.Items(row).Text
Dim found As Boolean
For Each item2 As ListViewItem In ListView2.Items
If text.Contains(item2.Text) Then
found = True
Exit For
End If
Next
If found Then numFound += 1
Next
If numFound > 0 Then MessageBox.Show("At least one of the first " & checkrows.ToString & " rows in ListView1 matches a row in ListView2")
If numFound = checkrows Then MessageBox.Show("The first " & checkrows.ToString & " rows in ListView1 match a row in ListView2")

Related

Insert custom text on datagridview row export to TXT

For the code below, I want to put at the beginning of each line exported in TXT the following text : "S,1,___,,;" + the row exported from database.
How can I add for each line that text on export? For the moment I have the text only on the firs line ( check pictures attached)
If DataGridView1.RowCount = 0 Then
MessageBox.Show("Lista este goala")
Else
If Directory.Exists("C:\test") = False Then
Directory.CreateDirectory("C:\test")
End If
Dim sFile As String = "C:\test\test.txt"
If File.Exists(sFile) = True Then
My.Computer.FileSystem.DeleteFile(sFile,
FileIO.UIOption.OnlyErrorDialogs,
FileIO.RecycleOption.DeletePermanently, FileIO.UICancelOption.DoNothing)
End If
Using f As New IO.StreamWriter(sFile, True)
Dim col As String = ""
Dim a As String = "S,1,______,_,__;"
Dim row As String = ""
Dim i As Integer = 0
For Each r As DataGridViewRow In DataGridView1.Rows
For Each c As DataGridViewColumn In DataGridView1.Columns
row = row & Convert.ToString(r.Cells(c.HeaderText).Value) & ";"
Next
If i < DataGridView1.Rows.Count - 1 Then row &= Environment.NewLine
Next
f.WriteLine(a & row)
End Using
Using f2 As New IO.StreamWriter(sFile, True)
Dim col As String = ""
Dim row As String = ""
Dim i As Integer = 0
For Each r As DataGridViewRow In DataGridView3.Rows
For Each c As DataGridViewColumn In DataGridView3.Columns
row = row & Convert.ToString(r.Cells(c.HeaderText).Value) & ";"
Next
If i < DataGridView3.Rows.Count - 1 Then Row &= Environment.NewLine
Next
f2.WriteLine("T,1,______,_,__;" & row)
f2.Close()
MessageBox.Show("Bon printat")
End Using
End If
And also a picture with exported file:
the red circled line is the way that I need for export
the red circle string from code is my input which is mandatory for each line followed by DGV lines export.
Actual TXT export
Actual Code for input my mandatory text before DGV export
Thanks!
Provide some debug detail like what is Rows.Count etc.
If it is not going inside loop and even there are rows, better you try with accessing object in DataSource.
Something like ForEach loop on ((DataTable)DataGridView1.DataSource).Rows

Throw ID and its information into listview

I got multiline textbox and ListView
textbox contains :
[1000]
name=John
number0=78569987
[1001]
name=Sara
number0=89768980
number1=77897545
TextBox2.Text = TextBox2.Text.Replace("[", "this what i want")
Dim lines As New List(Of String)
lines = TextBox2.Lines.ToList
Dim FilterText = "this what i want"
For i As Integer = lines.Count - 1 To 0 Step -1
If Not Regex.IsMatch(lines(i), FilterText) Then
lines.RemoveAt(i)
End If
Next
TextBox2.Lines = lines.ToArray
TextBox2.Text = TextBox2.Text.Replace("this what i want", "")
TextBox2.Text = TextBox2.Text.Replace("]", "")
ListBox1.Items.AddRange(TextBox2.Lines)
For Each x As String In ListBox1.Items
Dim II As New ListViewItem
II.Text = x
ListView1.Items.Add(II)
Next
I cant use the same way to insert numbers and names because some ids contain number0 number 1 and some contain only number 0 ,, so how can I insert their numbers ?
Thanks in advance.
Check the below code with comments. You might have to modify slightly to fit the data.
Check this question and it's linked questions for similar thing.
Edit: Note that this only copies from rows in richtextbox to different columns in listview, so it will work for the examples you provided. I hope you can refine this logic to account for specific columns as per the data coming in the richtextbox.
Dim lines As New List(Of String)
lines = TextBox2.Lines.ToList
'Add 1st row to the listview
ListView1.Items.Add(New ListViewItem())
'Use Counter to determine row#
Dim j As Integer = 0
'Loop through the items
For i As Integer = 0 To lines.Count - 1
'Check if it's 1st item i.e. ID and add as text (i.e. at Index 0)
If lines(i).StartsWith("[") Then
ListView1.Items(j).Text = lines(i).Substring(1, lines(i).Length - 2)
'Check if contains other columns with attributes
ElseIf lines(i).Contains("=") Then
ListView1.Items(j).SubItems.Add(lines(i).Substring(lines(i).IndexOf("=") + 1))
'Check if it's an empty record, and add new row to listview
Else
j = j + 1
ListView1.Items.Add(New ListViewItem())
End If
Next

What is causing 'Index was outside the bounds of the array' error?

What is causing 'Index was outside the bounds of the array' error? It can't be my file, defianetly not. Below is my code:
Sub pupiltest()
Dim exitt As String = Console.ReadLine
Do
If IsNumeric(exitt) Then
Exit Do
Else
'error message
End If
Loop
Select Case exitt
Case 1
Case 2
Case 3
End Select
Do
If exitt = 1 Then
pupilmenu()
ElseIf exitt = 3 Then
Exit Do
End If
Loop
Dim score As Integer
Dim word As String
Dim totalscore As Integer = 0
'If DatePart(DateInterval.Weekday, Today) = 5 Then
'Else
' Console.WriteLine("You are only allowed to take the test on Friday unless you missed it")
' pupiltest()
'End If
Dim founditem() As String = Nothing
For Each line As String In File.ReadAllLines("F:\Computing\Spelling Bee\stdnt&staffdtls.csv")
Dim item() As String = line.Split(","c)
founditem = item
Next
Dim stdntfname As String = founditem(3)
Dim stdntsname As String = founditem(4)
Dim stdntyear As String = founditem(5)
Console.Clear()
If founditem IsNot Nothing Then
Do
If stdntyear = founditem(5) And daytoday = founditem(6) Then
Exit Do
ElseIf daytoday <> founditem(6) Then
Console.WriteLine("Sorry you are not allowed to do this test today. Test available on " & item(6).Substring(0, 3) & "/" & item(6).Substring(3, 6) & "/" & item(6).Substring(6, 9))
Threading.Thread.Sleep(2500)
pupiltest()
ElseIf stdntyear <> founditem(5) Then
Console.WriteLine("Year not found, please contact the system analysts")
Threading.Thread.Sleep(2500)
pupiltest()
End If
Loop
End If
For Each line As String In File.ReadAllLines("F:\Computing\Spelling Bee\testtests.csv")
Dim item() As String = line.Split(","c)
Dim mine As String = String.Join(",", item(2), item(3), item(4), item(5), item(6))
For i As Integer = 1 To 10
Console.WriteLine(i.ToString & "." & item(1))
Console.Write("Please enter the word: ")
word = Console.ReadLine
If word = Nothing Or word <> item(0) Then
score += 0
ElseIf word = item(0) Then
score += 2
ElseIf word = mine Then
score += 1
End If
Next
If score > 15 Then
Console.WriteLine("Well done! Your score is" & score & "/20")
ElseIf score > 10 Then
Console.WriteLine("Your score is" & score & "/20")
ElseIf score Then
End If
Next
Using sw As New StreamWriter("F:\Computing\Spelling Bee\stdntscores", True)
sw.Write(stdntfname, stdntsname, stdntyear, score, daytoday, item(7))
Try
Catch ex As Exception
MsgBox("Error accessing designated file")
End Try
End Using
End
End Sub
All help is highly appreciated,
You are constantly replacing the foundItem array when you do founditem = item:
Dim founditem() As String = Nothing
For Each line As String In File.ReadAllLines("F:\Computing\Spelling Bee\stdnt&staffdtls.csv")
Dim item() As String = line.Split(","c)
founditem = item
Next
Also, you are using (=) the assignment operation instead of (==) relational operator, to compare. Refer to this article for help in understanding the difference between the two.
Instead of this: If stdntyear = founditem(5) And daytoday = founditem(6) Then
Use this: If (stdntyear == founditem(5)) And (daytoday == founditem(6)) Then
Now back to your main error. You continue to assign the itemarray to founditem every time you iterate (Which overwrites previous content). At the end of the Iteration you will be left with the last entry in your CSV only... So in other words, founditem will only have 1 element inside of it. If you try to pick out ANYTHING but index 0, it will throw the exception index was outside the bounds of the array
So when you try to do the following later, it throws the exception.
Dim stdntfname As String = founditem(3) 'index 3 does not exist!
To fix it do the following change:
Dim founditem() As String = Nothing
For Each line As String In File.ReadAllLines("F:\Computing\Spelling Bee\stdnt&staffdtls.csv")
'NOTE: Make sure you know exactly how many columns your csv has or whatever column
' you wish to access.
Dim item() As String = line.Split(","c)
founditem(0) = item(0) 'Assign item index 0 to index 0 of founditem...
founditem(1) = item(1)
founditem(2) = item(2)
founditem(3) = item(3)
founditem(4) = item(4)
founditem(5) = item(5)
founditem(6) = item(6)
Next
For more help on how to work with VB.NET Arrays visit this site: http://www.dotnetperls.com/array-vbnet
In your line Dim item() As String = line.Split(","c) there's no guarantee that the correct number of elements exist. It's possible that one of the lines is missing a comma or is a blank trailing line in the document. You might want to add a If item.Length >= 7 and skipping rows that don't have the right number of rows. Also, remember that unlike VB6, arrays in .Net are 0 based not 1 based so make sure that item(6) is the value that you think it is.

VB.NET: How to dynamically select a list view item?

I need to dynamically select an item in a listview based on what was selected previously.
The items that have been selected in the past are retrieved from a database and added to an Arraylist. These items then need to be selected from a number of different listviews.
Doing this by index like so listRef1.Items(2).Checked = True is no problem but I need to do it by the item text, i.e. one of the strings in the array.
So far I have this:
For i As Integer = 0 To refsArr.Count - 1
'find the correct category id
Dim cmdRefCat As New SqlCommand("SELECT RefID from ReferencesListTable WHERE RefName = '" & refsArr(i) & "'", conn)
Dim refid As Integer = cmdRefCat.ExecuteScalar()
If refid = 1 Then
listRef1.Items(refsArr(i)).Checked = True
ElseIf refid = 2 Then
listRef2.Items(refsArr(i)).Selected = True
listRef2.Select()
ElseIf refid = 3 Then
listRef3.Items.Item(refsArr(i)).Selected = True
listRef2.Select()
ElseIf refid = 4 Then
listRef4.Items.Item(refsArr(i)).Selected = True
End If
Next
Has anyone got any ideas on this? Thanks.
You'll need to loop through each item in the listview list:
For I as Integer = 0 to ListView.Items.Count - 1 Do
If ListView.Items(i).Text = "Text" then
ListView.Items(i).Selected = true
End If
End For
You can try this ...
For i As Integer = 0 To refsArr.Count - 1
'find the correct category id
Dim cmdRefCat As New SqlCommand("SELECT RefID from ReferencesListTable WHERE RefName = '" & refsArr(i) & "'", conn)
Dim refid As Integer = cmdRefCat.ExecuteScalar()
Select case refid
case 1
CheckIt(refsArr(i),listRef1)
case 2
CheckIt(refsArr(i),listRef2)
case 3
CheckIt(refsArr(i),listRef3)
case 4
CheckIt(refsArr(i),listRef4)
End Select
Next
And Sub CheckIt
Sub CheckIt(ByVal sRef as String, ByRef lvw as Listview)
Dim x as Integer
For x = 0 to lvw.Items.Count - 1
If lvw.Items(x).Text = sRef then
lvw.Items(x).Selected = true
exit for '-- if only 1 record
End If
Next
End Sub
The code to select an item dynamically from the listview control can be as follows for vb.net.
Let lvwomominiChair1 is the name of the listview control.
Set its fullrowselect property as true.
The code will select the text in the first column of the listview control.
Private Sub lvwomominiChair1_Click(sender As Object,e As EventArgs) Handles lvwomominiChair1.Click
Dim lvwitem as ListViewItem
lvwitem = lvwomominiChair1.SelectedItems.Item(0)
MsgBox("Selected item is " + lvwitem.Text)
End Sub
There may be situations where we need to get all items in a row of a ListView control.The following code may be used for the purpose.It is assumed that there are five columns of data in a raw and are of the text data type.This can be done with a For..Next loop as follows.Let 0,1,2,3 and 4 are the five column indices.
Private Sub lvwomominiChair1_Click(sender As Object,e As EventArgs) Handles lvwomominiChair1.Click
Dim i As Int32
Dim str As String
str =""
For i =0 To 4
str = str + " " + lvwomominiChair1.SelectedItems(0).SubItems(i).Text
Next
MsgBox("Selected items of the five columns of the row are " + str)
End Sub
Or you can do this, works perfect for me:
ListView.Items(0).Selected = True
ListView.Select()

Remove items from listview

I have a listview that has multiple entries and each entry has 2 subitems. I am wanting to know how to remove each item in the listview where the subitem(1) equals a certain string.
What would be the best way to do this?
thanks
You can't use a for..each loop to remove items. after you remove the first item, the for...each is broken.
Try this:
Dim pos As Int32
Dim listItem As ListViewItem
For pos = lvw.Items.Count - 1 To 0 Step -1
listItem = lvw.Items(pos)
If listItem.SubItems(1).Text = "testvalue" Then
lvw.Items.Remove(listItem)
End If
Next
Dim listItem As ListViewItem
Dim someName As String
For Each listItem In lvw.Items
If listItem.Text = someName Then
lvw.Items.Remove(listItem)
' If you only want to remove one item with that Text
' you can put an Exit For right here
End If
Next
You can try something like this.
For Each listItem As ListViewItem In ListView1.Items
If listItem.SubItems.Item(1).Text = "SomeName" Then
listItem.Remove()
End If
Next
This is probably the easiest way of removing all the list items.
Do While YOURITEMLIST.Items.Count <> 0
YOURITEMLIST.Items.Remove(YOURITEMLIST.Items(0))
Loop
Dim x As Integer = 0
For Each item6 As ListViewItem In ListView4.Items
Dim f As String = item6.SubItems(1).Text
Dim ind As Integer = item6.Index
For Each item7 As ListViewItem In ListView4.Items
Dim f2 As String = item7.SubItems(1).Text
' MsgBox(f & " 2nd value " & f2)
If (f = f2) Then
x = x + 1
' MsgBox(x & "= time matched" & f)
If (x > 1) Then
MsgBox("delete here")
ListView4.Items.Remove(item6)
End If
End If
Next
x = 0
Next