count number of strings in listbox

mirzao

Active member
Joined
Nov 10, 2005
Messages
44
Location
Malaysia
Programming Experience
Beginner
I'm writing a function to count how many times the code "503" happened in listbox2 and 3 but it doesn't work. I wonder why. I'm very new to programming so plz help me.The following are my code:

Private Sub button2_click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
oCP =
New Rs232
Dim i, j, m, o As Integer
For j = 1 To 2
For i = 2 To 3 'COM 2 to 3
Try
With oCP
.Port = i
.BaudRate = 9600
.Parity = Rs232.DataParity.Parity_None
.DataBit = 8
.StopBit = Rs232.DataStopBit.StopBit_1
End With
oCP.Open()
MessageBox.Show("COM " & i.ToString & " opened")
oCP.Write(Encoding.ASCII.GetBytes("strs" & Chr(13)))
' As long as there is information, read one byte at a time and output it.
Try
While (oCP.Read(1) <> -1) 'get byte frm port
WriteMessage(oCP.InputStreamString, False)
End While
Catch exc As Exception
End Try
m = TextBox1.Lines.Length
Dim myArray() As String
myArray = TextBox1.Lines(m - 3).Split(" "c) 'split each code in line m
For o = LBound(myArray) To UBound(myArray) - 1
Me.ListBox2.Items.Add(myArray(o))
Next
If Me.ListBox2.Items.Count <> 0 Then
countjam()
MessageBox.Show("COM " & i.ToString & " has " & countjam() & " jam.")
TextBox5.Text = countjam()
End If
ListBox2.Items.Clear()
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Exclamation, "Connection Error")
End Try


If oCP.IsOpen Then oCP.Close()
MessageBox.Show("COM " & i.ToString & " closed")
Next
Next
End Sub


Public Function countjam() As Integer
Dim count As Integer
For i As Integer = 0 To ListBox2.Items.Count - 1

'Dim str As String = "503"
'For Each str In ListBox2.Items
'count += 1
ListBox2.SetSelected(i, True)
If ListBox2.SelectedItems(i) = "503" Or "406" Then
count += 1
End If
Next
countjam = count
End Function
 
Last edited:
VB.NET:
[SIZE=2][COLOR=#0000ff]For[/COLOR][/SIZE][SIZE=2] [/SIZE][SIZE=2][COLOR=#0000ff]Each[/COLOR][/SIZE][SIZE=2] str [/SIZE][SIZE=2][COLOR=#0000ff]As[/COLOR][/SIZE][SIZE=2] [/SIZE][SIZE=2][COLOR=#0000ff]String[/COLOR][/SIZE][SIZE=2] [/SIZE][SIZE=2][COLOR=#0000ff]In[/COLOR][/SIZE][SIZE=2] lst.Items
[/SIZE][SIZE=2][COLOR=#0000ff]If[/COLOR][/SIZE][SIZE=2] str = [/SIZE][SIZE=2][COLOR=#800000]"503"[/COLOR][/SIZE][SIZE=2] [/SIZE][SIZE=2][COLOR=#0000ff]Then[/COLOR][/SIZE][SIZE=2] count += 1
[/SIZE][SIZE=2][COLOR=#0000ff]Next
[/COLOR][/SIZE]
 
I've tried before, but it also count other code instead of "503". I think the arrangement of my code is not right. Actually, where's the right place to put it.
 
Last edited:
Back
Top