Getting the text of a listview subitem - vb.net

I am trying to get the text of a ListView subitem in vb.net. according to this answer, the below code should work.
Function gen() As String
Dim Log = New Logging.Log("gen")
Dim Code As String = getTemplateCode()
For Each i As ListViewItem In ListView1.Items
Log.WriteEntry("Item: " + i.Text)
If i.SubItems.Count > 0 Then
Log.WriteEntry("Item: " + i.SubItems(0).Text)
Code = Code.Replace(i.Text, i.SubItems(0).Text)
End If
Next
Return Code
End Function
However, instead of getting string in ListViewItem.SubItem.Text, i am getting what seems to be the ListViewItem.Text, and cant figure out why.
Here's the actual log output from the above code:
gen Information: 0 : Item: $Parshah$
gen Information: 0 : Item: $Parshah$
gen Information: 0 : Item: $Year$
gen Information: 0 : Item: $Year$
gen Information: 0 : Item: $EnglishId$
gen Information: 0 : Item: $EnglishId$
gen Information: 0 : Item: $books$
gen Information: 0 : Item: $books$
gen Information: 0 : Item: $title$
gen Information: 0 : Item: $title$
and a screenshot of the listview
The log output should've been
gen Information: 0 : Item: $Parshah$
gen Information: 0 : Item: nothing
gen Information: 0 : Item: $Year$
gen Information: 0 : Item: nothing
gen Information: 0 : Item: $EnglishId$
gen Information: 0 : Item: nothing
gen Information: 0 : Item: $books$
gen Information: 0 : Item: nothing
gen Information: 0 : Item: $title$
gen Information: 0 : Item: nothing
What am I doing wrong?

Ok. Stupid mistake. A drop of research told me that a ListViewItem contains itself in its first subitem, and the first dynamically added subitem starts with an index of one instead of zero. (oops.)
Think Batch Arguments where %~0 is the file itself... lol.
SO, we change the code like this:
Function gen() As String
Dim Log = New Logging.Log("gen")
Dim Code As String = getTemplateCode()
For Each i As ListViewItem In ListView1.Items
Log.WriteEntry("Item: " + i.Text)
If i.SubItems.Count > 0 Then
Log.WriteEntry("Item: " + i.SubItems(1).Text) 'changed 0 to 1
Code = Code.Replace(i.Text, i.SubItems(1).Text) 'changed 0 to 1
End If
Next
Return Code
End Function

Related

Reading an array following a 2 level string.split

Newbie question. I can't figure this out.
I have string "48,1;49,2;50,0" which I have split using :
Dim splitAtSemiColon() As String = strPatientMed.Split(";"c)
Dim result() = splitAtSemiColon.Select(Function(x) x.Split(","c)).ToArray()
In the Visual studio interface, I can see that this results in:
Result(0) contains (0) = "48" and (1) = "1"
Result(1) contains (0) = "49" and (1) = "2"
Result(2) contains (0) = "50" and (1) = "0"
But how do I loop to read this array using code i.e. how do I read the (0) and (1) portion of each result item?
Thanks all!
Sub Main()
Dim strPatientmed = "48,1;49,2;50,0"
Dim splitAtSemiColon() As String = strPatientMed.Split(";"c)
Dim result() = splitAtSemiColon.Select(Function(x) x.Split(","c)).ToArray()
'Result is an Array of arrays, each inner array has only 2 elements (first & last)
For Each element In result
'For each <array> in result
'result(0) -> <element> -> [48|1]
'<element>.First = 48 | <element>.Last = 1
Console.WriteLine($"Before comma: {element.First} | After comma: {element.Last}")
Next
End Sub
Result
Before comma: 48 | After comma: 1
Before comma: 49 | After comma: 2
Before comma: 50 | After comma: 0

Searching text file and showing part of the text in a text box

I am working on a VB.net application where I have a very large text file. It is basically a large database of error codes with descriptions of how to clear the code after it. What I would like to do, is on the click of a button, search the text file for the specific code and display all text for just that error code into a text box. I have tried many different ways, but am unable to get it to work properly. I went through the entire text file and added a "|" to the beginning of each fault code so that I could specify where the code starts at.
Here is an example of a couple fault codes:
|ACAL-000 Fail to run DETECT Motn Cause: The AccuCal2 Motion failed to
nm. The AccuCal2 motion cannot be started. Remedy: Clear all the
errors before executing AccuCal2. |ACAL-001 Robot is not ready.
Cause: The robot is not ready. The system cannot issue motion
because it is in an error state. Remedy: Clear all faults, then retry
the operation.
If I search for "ACAL-000", I want it to show everything from the | before ACAL-000 to the bar before ACAL-001.
I would post the code that I have written, but I have tried so many different versions that I don't really know which one to post.
Any help you can provide would be greatly appreciated.
EDIT
Here is my current code after some editing and implementation of what has been recommended. Please see the comments below for more information on how I got to this point. A quick note, I am currently just using "|ACAL-000" for a test search. When this is complete, I have some other (already working) code that will put together a code from a couple of drop down lists.
Function ReadEmbeddedTextFileResource(embeddedResourceName As String) As String
Using stream As Stream = Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream(embeddedResourceName)
If stream Is Nothing Then
Throw New FileNotFoundException("The resource '" & embeddedResourceName & "' was not found.")
End If
Using reader As StreamReader = New StreamReader(stream, True)
Return reader.ReadToEnd()
End Using
End Using
End Function
Function FindTextBetweenBars(bodyOfTextToSearch As String, textToLookFor As String) As String
Dim i As Integer = bodyOfTextToSearch.IndexOf(textToLookFor)
If i < 0 Then Return Nothing
Dim j As Integer = bodyOfTextToSearch.LastIndexOf("|", i)
If j < 0 Then j = 0
Dim k As Integer = bodyOfTextToSearch.IndexOf("|", i + Len(textToLookFor))
If k < 0 Then k = Len(bodyOfTextToSearch)
Return bodyOfTextToSearch.Substring(j + 1, k - j - 1)
End Function
Private Sub btnShowTroubleshooting_Click(sender As Object, e As EventArgs) Handles btnShowTroubleshooting.Click
Dim allErrorText As String = ReadEmbeddedTextFileResource(My.Resources.FanucCodes)
Dim errorMessage As String = FindTextBetweenBars(allErrorText, "|ACAL-000")
If errorMessage Is Nothing Then errorMessage = "Error code Not found!"
RichTextBoxFanucFaults.Text = errorMessage
End Sub
Here is a function that should do what you want:
Function FindTextBetweenBars(bodyOfTextToSearch As String, textToLookFor As String) As String
Dim i As Integer = bodyOfTextToSearch.IndexOf(textToLookFor)
If i < 0 Then Return Nothing
Dim j As Integer = bodyOfTextToSearch.LastIndexOf("|", i)
Dim k As Integer = bodyOfTextToSearch.IndexOf("|", i + Len(textToLookFor))
If k < 0 Then k = Len(bodyOfTextToSearch)
Return bodyOfTextToSearch.Substring(j + 1, k - j - 1)
End Function
In your button click event handler you can call the function like this:
Dim errorMessage as String = FindTextBetweenBars(My.Resources.FanucCodes, txtErrorCodeToLookFor.Text)
If errorMessage Is Nothing Then errorMessage = "Error code not found!"
txtErrorMessage.Text = errorMessage
where txtErrorMessage is the output textbox to display the error message result,
My.Resources.FanucCodes is your large string resource containing all the error descriptions (with | separators), and txtErrorCodeToLookFor is a textbox that accepts the error code input from the user.

trying to to get specifically ordered data from .txt and then converting and storing it to double or string arrays at visual basic

I am trying, for several days, to take specifically ordered data from a .txt file and then convert and store it to double or string arrays
the data is stored in the file in this way:
1 0 1 0 >= 15
0 1 0 1 >= 28
1 1 0 0 <= 30
0 0 3 1 <= 22
-1 0 2 0 <= 0
(one line after the other with no blank lines between them)
and my code for this goes like:
Using stream As System.IO.FileStream = System.IO.File.OpenRead("C:\Users\user\Desktop\test_new.txt")
Using reader As New System.IO.StreamReader(stream)
Dim lineCount = File.ReadAllLines("C:\Users\user\Desktop\test_new.txt").Length
Dim line As String = reader.ReadLine()
Dim aryTextFile() As String
Dim operator1() As String
Dim variables(,) As Double
Dim results() As Double
Dim counter3 As Integer
counter3 = 0
NRows = lineCount
While (line IsNot Nothing)
Dim columns = line.Split(" ")
aryTextFile = line.Split(" ")
line = reader.ReadLine()
NVars = columns.Length - 3
For j = 0 To UBound(aryTextFile) - 3
variables(counter3, j) = CDbl(aryTextFile(j))
Next j
For j = NVars To UBound(aryTextFile) - 2
operator1(counter3) = CStr(aryTextFile(j))
Next j
For j = UBound(aryTextFile) - 2 To UBound(aryTextFile) - 1
results(counter3) = CDbl(aryTextFile(j))
Next j
counter3 = counter3 + 1
End While
End Using
End Using
I'm getting warnings which result in errors ofc.
Variable 'variables' is used before it has been assigned a value. A null reference exception could result at
runtime. C:\Users\user\Documents\Visual Studio
2008\Projects\WindowsApplication1\WindowsApplication1\Form1.vb 230 25 WindowsApplication1
Variable 'operator1' is used before it has been assigned a value. A null reference exception could result at
runtime. C:\Users\user\Documents\Visual Studio
2008\Projects\WindowsApplication1\WindowsApplication1\Form1.vb 236 25 WindowsApplication1
Variable 'results' is used before it has been assigned a value. A null reference exception could result at
runtime. C:\Users\user\Documents\Visual Studio
2008\Projects\WindowsApplication1\WindowsApplication1\Form1.vb 243 25 WindowsApplication1
So what am I doing wrong and how can I fix it
note: data is saved from dynamic matrixes, so it can be a lot bigger than the displayed example (several lines with several columns), and that is the reason I'm trying to program it, in order to save me some lab time of copying and pasting it manually...
thanks in advance,
Viktor
p.s. if another member or admin can indicate an older post about my question, that would also be very helpful, but I am reading posts for the last 4 days in similar questions and I couldn't find something working for me
p.s.2 since is my first post, I have also tried to attach the project and I couldn't find a way :)
You need to define the dimensions of your arrays before trying to use them.
If you don't know what the size will be use a list instead.
'No defined size - Warning
Dim array1() As String
'Error when trying to access
array1(4) = "Testing"
'Defined size
Dim array2(10) As String
array2(5) = "Testing"

InvalidArgument=Value of '5' is not valid for 'index'.

Well, merry christmas all!
I am having trouble with the following whilst writing my chatroom program. I am adding an item to a listview, but when i try to add text to the last subitem, I get the error InvalidArgument=Value of '5' is not valid for 'index'.
I have done the following:
msgbox(listview1.subitems.count())
and that returns 5, so I assume that means I have a total of 6 columns (the counting begins from 0 - 5 not 1 - 5.
What could be the problem? The rest of the code is:
Sub AddClient(ByVal client As connection, ByVal strings() As String)
Dim l As New ListViewItem(strings)
l.ImageIndex = GetFlag(strings(1).ToLower)
l.Tag = client
numcon1.Text += 1
l.SubItems(5).Text = "test phrase"
l.SubItems(4).Text = strings(7)
addtoconsole(strings(3) & " ~ " & strings(1) & " Has Connected.")
ListView1.Items.Add(l)
If audiocon = "True" Then
My.Computer.Audio.Play("newuser.wav", AudioPlayMode.Background)
Else
End If
If notifcon = "True" Then
NotifyIcon1.ShowBalloonTip(3000, "A friend is online!", strings(3) & " ~ " & strings(1), ToolTipIcon.Info)
End If
End Sub
thanks so much!
that returns 5, so I assume that means I have a total of 6 columns (the counting begins from 0 - 5 not 1 - 5.
No. It means 5 columns in total. Starting with index 0 and ending with index 4.

display selectedItems in a label

I need to display the selecteditems in a label
I am using VB 2005
I set the selection mode to multi-extended
It did work selecting only one item with the following code:
me.xresultslabel.text= me.xlisttextbox.text.selectedItem.tostring
But when I tried to display more than one item using the following code:
me.resultlabel.text= me.xlisttextbox.text.selectedItems, I get the following string on the label:
system.windows.forms.listbox+selectedobjetcollections.
any help will be highly appreciate
Dim collection = Me.xlisttextbox.Text.SelectedItems
Dim builder As New StringBuilder()
For i As Integer = 0 To collection.Count - 1
If i > 0 Then builder.Append(", ")
builder.Append(collection(i))
Next
Me.resultlabel.Text = builder.ToString