Throw ID and its information into listview - vb.net

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

Related

vb- How to assign a different tag property to different array words?

This is my code for inserting from textfile to array to labels, but I want to be able to assign a tag property onto some of the words or perhaps use the 'Answer' which is located a line below on my text file??
IndexNo = 0
Dim FileTerm As String = "D:\soccer.txt"
Dim FileNum As Integer = FreeFile()
FileOpen(FileNum, FileTerm, OpenMode.Input)
Do
Term(IndexNo) = LineInput(FileNum)
Answer(IndexNo) = LineInput(FileNum)
IndexNo = IndexNo + 1
Loop Until EOF(FileNum)
FileClose(FileNum)
Dim Obj As Object, Count As Integer = 0
For Each Obj In Me.Controls
If TypeOf Obj Is Label Then
MyLabels(Count) = Obj
Count = Count + 1
End If
Next
Dim Random1, Random2 As Integer
Dim TempTerm, TempAnswer As Object
For Count = 0 To 15
Randomize()
Random1 = Val(Int(16 * Rnd()))
Random2 = Val(Int(16 * Rnd()))
TempTerm = Term(Random1)
Term(Random1) = Term(Random2)
Term(Random2) = TempTerm
TempAnswer = Answer(Random1)
Answer(Random1) = Answer(Random2)
Answer(Random2) = TempAnswer
Count = Count + 1
Next
For Count = 0 To 15
MyLabels(Count).Text = Term(Count)
Next
If anyone has any ideas, the help is appreciated. Thanks
Even though your question is not very clear. From what I get, you want to have some way to keep your Labels and the corresponding Term and Answers in sync.
There are many ways to do this, but I would prefer to do it as below... the perfect VB.NET way as opposed to using any legacy VB6 techniques.
First declare a class that would keep our Term and Answers in one object. This is the equivalent of Type in VB6.
Public Class TermAnswer
Public Term As String
Public Answer As String
' you may add more fields/properties here if you wish to...
End Class
Now it is easy to code our solution.
' declare a Dictionary object with Label as key and the corresponding Term and Answers as values.
Dim TermAnswers As New Dictionary(Of Label, TermAnswer)
' this is a temporary List to hold our Term and Answers read from file until we randomize them.
Dim tempTermAnswers As New List(Of TermAnswer)
' Our Labels array... yes it is this easy :)
Dim myLabels() As Label = Me.Controls.OfType(Of Label)().ToArray
' read our file into the tempTermAnswers List
Dim FileTerm As String = "D:\soccer.txt"
Using reader As New IO.StreamReader(FileTerm)
While Not reader.EndOfStream
Dim ta As New TermAnswer
ta.Term = reader.ReadLine
ta.Answer = reader.ReadLine
tempTermAnswers.Add(ta)
End While
reader.Close()
End Using
' pick Term Answers from our tempTermAnswers List randomly and add them to our TermAnswers Dictionary
' we also set our Label text here, though you can loop separately too
Dim randomNumbers As New Random
Dim tempTerm As TermAnswer, randomNumber As Integer
For Each label In myLabels
randomNumber = randomNumbers.Next(0, tempTermAnswers.Count)
tempTerm = tempTermAnswers(randomNumber)
TermAnswers.Add(label, tempTerm)
tempTermAnswers.Remove(tempTerm)
label.Text = tempTerm.Term
Next
' now you have your term answers in a Dictionary, indexed by Label.
' you can get any of them by providing a Label on your form as key and get the corresponding Term and Answer as value.
' e.g. let us list the Label Name, Term and Answer in our debug window...
For Each label In myLabels
Debug.WriteLine(label.Name & " ... " & TermAnswers(label).Term & " ... " & TermAnswers(label).Answer)
Next

Check if first 3 items in listview1 matches one of listview2's items

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")

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.

How can I parse records from a text file to an array?

here is a snippet of the file,
Year 1
mandatory
COM137,Mathematics for Computing,20,2
COM140,Computer Technologies,1-2,20
COM147,Introduction to databases,1-2,20
Year 2
optional
COM606 ..... etc
I want from this an array that reads
COM317,Mathematics for Computing,20,2,M,Year1
COM140,Computer Technologies,1-2,20,M,Year1
this is the layout of each element in the array that i want, but i have no idea how to do it, so the app reads the document see's year 1 stores that in current year then reads mandatory stores that as M in a variable, then i want to add that to an array, then when it sees year 2 it starts again year 2 added to the array element instead.. this is the what i have attempted so far
Dim arrModules As String()
Dim count As Integer = 0
Dim sr As StreamReader = New StreamReader("datasource.txt")
Dim line = sr.ReadLine() ' get each line and store it
Dim currentYear As Integer
Dim moduleStats As String = ""
Dim modArray As String()
While Not sr.EndOfStream
If line.Contains("Year") Then
currentYear = line
ElseIf line.Contains("mandatory") Then
moduleStats = "M"
ElseIf line.Contains("optional") Then
moduleStats = "O"
ElseIf line.Contains("COM") Then
modArray = sr.ReadLine.Split(",")
MsgBox(modArray)
End If
count += 1
sr.ReadLine()
End While
End
// in here is where i am having the problem i don't know how to get all the information i need into one specific array element within an array.. i want to get the year and the module status added to the end of an array element
This being Visual Basic, you could make room for the last two elements this way:
Dim i As Integer = modArray.Length
ReDim Preserve modArray((i - 1) + 2)
modArray(i) = moduleStats
modArray(i + 1) = currentYear.ToString()
Copy the result from Split to a new, larger array and add the additional info.
Dim modArray As String() = {"A", "B", "C"}
Dim finalArray As String() = New String(modArray.Length + 1) {}
Array.Copy(modArray, finalArray, modArray.Length)
finalArray(finalArray.Length - 2) = "M"
finalArray(finalArray.Length - 1) = "Year1"
Or you can simply use
ReDim Preserve modArray(modArray.Length+2)
modArray(modArray.Length - 2) = "M"
modArray(modArray.Length - 1) = "Year1"

Need help with VB.NET List Logic

Hey guys, so I am creating a List(Of String), always of size 9.
This list contains True/False values. I need to go through this list and find the 3 values that are True (will never be more than 3, but could be less) and then set 3 string values in my code to the 3 index's of those values + 1.
Here is my current code:
Private Sub SetDenialReasons(ByVal LoanData As DataRow)
Dim reasons As New List(Of String)
With reasons
.Add(LoanData.Item("IsDenialReasonDTI").ToString)
.Add(LoanData.Item("IsDenialReasonEmploymentHistory").ToString)
.Add(LoanData.Item("IsDenialReasonCreditHistory").ToString)
.Add(LoanData.Item("IsDenialReasonCollateral").ToString)
.Add(LoanData.Item("IsDenialReasonCash").ToString)
.Add(LoanData.Item("IsDenialReasonInverifiableInfo").ToString)
.Add(LoanData.Item("IsDenialReasonIncomplete").ToString)
.Add(LoanData.Item("IsDenialReasonMortgageInsuranceDenied").ToString)
.Add(LoanData.Item("IsDenialReasonOther").ToString)
End With
Dim count As Integer = 0
For Each item As String In reasons
If item = "True" Then
count += 1
End If
Next
If count = 1 Then
DenialReason1 = (reasons.IndexOf("True") + 1).ToString
ElseIf count = 2 Then
DenialReason1 = (reasons.IndexOf("True") + 1).ToString
DenialReason2 = (reasons.LastIndexOf("True") + 1).ToString
ElseIf count >= 3 Then
Dim tempIndex As Integer = reasons.IndexOf("True")
DenialReason1 = (reasons.IndexOf("True") + 1).ToString
DenialReason2 = (reasons.IndexOf("True", tempIndex, reasons.Count - 1) + 1).ToString
DenialReason3 = (reasons.LastIndexOf("True") + 1).ToString
End If
End Sub
I had 3 True's next to each other in the array and the code failed with an exception saying count must be positive or something.
Now if there are less than 3 True's, it should set the remaining DenialReason's that haven't been set yet as blank (however they are set as blank in the constructor already to account for this).
Any ideas?
Perhaps you could modify your For Each code to handle the assignment of the DenialReasons. This still feels like a hack, but I think it may be cleaner that what you have. If you use this code, you don't need the code that begins with If count = 1...:
Dim count As Integer = 0
Dim index As Integer = 1
For Each item As String In reasons
If item = "True" Then
count += 1
Select Case count
Case 1
DenialReason1 = index.ToString()
Case 2
DenialReason2 = index.ToString()
Case 3
DenialReason3 = index.ToString()
End Select
End If
index += 1
Next
The index variable above assumes a 1-based index. I think this is cleaner than using IndexOf().
I think a better solution might be to have a list of DenialReasons and add to that list as items are true:
Dim count As Integer = 0
Dim index As Integer = 1
Dim denialReasons As New List(Of String)()
For Each item As String In reasons
If item = "True" Then
denialReasons.Add(index)
End If
index += 1
Next
Then you can simply iterate through your list of denialReasons. This is flexible so that if, for whatever reason, you have more than three DenialReasons, you don't have to add another hard-coded variable.