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

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.

Related

Monster Search - Loop (string search + integer insert)

I have a large string(over 255 char) called strMonsterEssay.
There is a string character repeated throughout this essay with exact format like Monster X and I want to be able to find the largest monster number. Throughout the essay there is Monster 1, Monster 2...Monster X. Note, there is a max number of 99 monsters possible.
At the end of the code I want to be able to say something like "There are 25 Monsters".
I don't know the syntax to enter an integer into a 'like' search loop. This is the code I have so far and I would appreciate some help, please:
Dim MonsterNum As Integer
Dim strHowManyMonsters As String
MonsterNum = 1
For MonsterNum 1 to 99
If (NOT strMonsterEssay like ("*Monster&Char(32)&'"MonsterNum + 1"'*") And strMonsterEssay like ("*Monster&Char(32)&'"MonsterNum"'*") Then strHowManyMonsters = "There are '"MonsterNum"' Monsters."
Else: strHowManyMonsters = "There are no Monsters."
End If
Next MonsterNum
Try this
Dim MonsterNum As Integer
Dim strHowManyMonsters As String
strHowManyMonsters = "There are no Monsters."
For MonsterNum = 99 To 1 Step -1
If strMonsterEssay Like "*[mM]onster " & MonsterNum & "*" Then
strHowManyMonsters = "There are " & MonsterNum & " Monsters."
Exit For
End If
Next MonsterNum
Note the usage of [mM] to test make the search not case-sensitive. I think it might be a better option to use VBA's Instr() function like this:
If InStr(1, strMonsterEssay, "Monster " & MonsterNum, vbTextCompare) > 0 Then
Also note the backward counting.
Use the next function, please. If all existing 'Monster' strings are followed by different numbers, the number does not matter. It is enough to count Monster.
Function CountMonsters(FullString As String, strMonster As String) As Long
CountMonsters = UBound(Split(FullString, strMonster))
End Function
It can be called in this way:
Sub testFindMonsters()
Dim strMonsterEssay As String
strMonsterEssay = "Monster 1 and Monster 2 goes to school. Monster 3 is waitting for the first two..."
MsgBox "There are " & CountMonsters(strMonsterEssay, "Monster") & " Monsters."
End Sub
If the "largest monster number" must be returned, the same function will be called in this way:
Sub testMaxMonsterNumber()
Dim MonsterNum As Long, strMonsterEssay As String, maxNo As Long, i As Long
Dim strHowManyMonsters As String
strMonsterEssay = "Monster 1 and Monster 2 goes to school. Monster 3 is waiting for the first two. However, Monster 1 and Monster 2 saw Monster 3 waiting and went a different way. Monster 3 waited for a long time for Monster 1 and Monster 2 but they never showed up"
For i = 99 To 1 Step -1
If CountMonsters(strMonsterEssay, "Monster " & i) > 0 Then
maxNo = i: Exit For
End If
Next
If maxNo > 0 Then
MsgBox "There are " & maxNo & " Monsters."
Else
MsgBox "There are no Monsters."
End If
End Sub
But if "Monster 32 is waiting for the first two", it will return 32. I asked you about consecutive monsters number 'rule', but you did not say anything...

Making text go to a new line when in a while loop

I have a richTextbox, and a while loop, x = 0, and every time this loop runs, x += 1 till it reaches a certain value.
Heres what I want to happen:
while x <> 10 then
it will say item 0 +1 on a new line, and then item 1 + 1 on the line under it, etc, so you will see all 10 values after.
What happens is, it will change that line into the new value.
My question is: How do I make it put the words on a new line instead?
Here is my code:
While readListItem <> PaymentList.Items.Count
If readListItem > PaymentList.Items.Count Then
readListItem = 0
Exit While
End If
readListItem += 1
MessageBox.Show(readListItem)
resultBox.Text = vbNewLine + PaymentList.Items.Item(readListItem) + " costs " + enteredCost + "." + vbNewLine
End While
readListItem is "x", and that is being iterated by 1 every time the loop runs
PaymentList is my listbox containing an unknown value (the user sets the number of items in this list)
The If if there because, after x = lets say 10, it would add another to x (so now it = 11) and try to print out the 11th item, as it doesnt exist, it crashes. This is to attempt to prevent that. I didnt want to go with a try catch
Try adding the new value instead of replacing the entire value:
resultBox.Text &= Environment.NewLine() & PaymentList.Items.Item(readListItem) + " costs " + enteredCost + "."
The expression &= is equivalent, in this case, to resultBox.Text = resultBox.Text & "...".
And once advice, you can simplify your loop by using this condition:
While readListItem < PaymentList.Items.Count
'...
End While

How to use CheckIfPrime

I need to use the CheckIfPrime item in my code, but having some issue, may i know how should I deal with it? Do I need to make declaration?
For number As Integer = 1 To 30
If CheckIfPrime(number) = True Then
sb.Append(number.ToString & " ")
End If
Next
Please advice on how can I do that in Visual Basic.
The VB.net has no CheckIfPrime method, so to deal with it in your task we need to create a method to check the number if is prime or not.
Public Function CheckIfPrime(number As Integer) As Boolean
For i As Integer = 2 To number - 1
If number Mod i = 0 Then
Return False
End If
Next
Return True
End Function
Usage
For number As Integer = 1 To 30
If CheckIfPrime(number) = True Then
'Console.WriteLine(number.ToString & " ")
sb.Append(number.ToString & " ")
End If
Next
Source

Check if a string variable has an integer value

I am working on a project which allows kids to send a message to Santa. Unfortunately, if they enter a string instead of an integer in the AGE field, the program crashes and returns Conversion from string "[exampleString]" to type 'Double' is not valid.
Is there any way to check if they have entered an integer or not? This is the code.
If childAge > 0 And childAge < 150 Then
fmSecA2 = "Wow! You are already " & childAge & " years old? You're growing to be a big " & childGender & " now! "
Else
fmSecA2 = "Erm, I couldn't really understand your age. Are you making this up? Ho ho ho!"
End If
Thanks,
Kai :)
A very simple trick is to try parse the string as an Integer. If it succeeds, it is an integer (surprise surprise).
Dim childAgeAsInt As Integer
If Integer.TryParse(childAge, childAgeAsInt) Then
' childAge successfully parsed as Integer
Else
' childAge is not an Integer
End If
Complementing Styxxy's response, if you dont need a result just replace it by vbNull:
If Integer.TryParse(childAge, vbNull) Then
You could perform the following two tests to be reasonably certain that the input you're getting is an integer:
If IsNumeric(childAge) AndAlso (InStr(1, childAge, ".") <> 0) Then
fmSecA2 = "Wow! You are already " & childAge & " years old? You're growing to be a big " & childGender & " now! "
If childAge < 0 OrElse childAge > 150 Then
fmSecA2 = "I don't believe it's possible to be" & childAge & " years old..."
End If
Else
fmSecA2 = "Erm, I couldn't really understand your age. Are you making this up? Ho ho ho!"
The InStr function returns zero if it doesn't find the string that is being looked for, and so when combining that test with IsNumeric, you also rule out the possibility that some floating point data type was entered.
IsNumeric is built into VB, and will return a true/false
If IsNumeric(childAge) AndAlso (childAge > 0 And childAge < 150) Then
fmSecA2 = "Wow! You are already " & childAge & " years old? You're growing to be a big " & childGender & " now! "
Else
fmSecA2 = "Erm, I couldn't really understand your age. Are you making this up? Ho ho ho!"
End If
You can use this.
Sub checkInt()
If IsNumeric(Range("A1")) And Not IsEmpty(Range("A1")) Then
If Round(Range("A1"), 0) / 1 = Range("A1") Then
MsgBox "Integer: " & Range("A1")
Else
MsgBox "Not Integer: " & Range("A1")
End If
Else
MsgBox "Not numeric or empty"
End If
End Sub
Working from Styxxy's answer, if you parse as a byte rather than an integer, then it also checks negative ages and maximum age of 255 all in one go.
Dim childAgeAsByte As Byte
If Byte.TryParse(childAge, childAgeAsByte) Then
' childAge successfully parsed as Byte
Else
' childAge is not a Byte
End If
Kristian
Dim Input
Input = TextBox1.Text
If Input > 0 Then
............................
............................
Else
TextBox2.Text = "Please only enter positive integers"
End If
Try
If TextBox1.Text > 0 Then
Label1.Text = "Integer"
End If
Catch ex As Exception
Label1.Text = "String"
End Try
With this you can put anything in TextBox1, if you put text then you get Label1 is string and if you put number then you get it's integer
In .Net you may use GetType() to determine the data type of a variable.
Dim n1 As Integer = 12
Dim n2 As Integer = 82
Dim n3 As Long = 12
Console.WriteLine("n1 and n2 are the same type: {0}",
Object.ReferenceEquals(n1.GetType(), n2.GetType()))
Console.WriteLine("n1 and n3 are the same type: {0}",
Object.ReferenceEquals(n1.GetType(), n3.GetType()))
' The example displays the following output:
' n1 and n2 are the same type: True
' n1 and n3 are the same type: False
Based on the above sample you can write a code snippet:
If childAge.GetType() = "Integer" then '-- also use childAge.GetType().Name = "Int32"
' do something
End if
Reference MSDN

VB.NET Infinite For Loop

Is it possible to write an infinite for loop in VB.NET?
If so, what is the syntax?
Do
Something
Loop
For i as Integer = 0 To 1 Step 0
If that's not hacky enough, can also write:
For i As Integer = 0 To 2
i -= 1
Next
or
while (true)
end while
ok, proper For answer:
Dim InfiniteLoop as Boolean = true;
For i = 1 to 45687894
If i = 45687893 And InfiniteLoop = true Then i = 1
End For
Aside from all the many answers given to make a loop run forever, this may just be the first that actually uses the value of Positive Infinity to cap the loop. Just to be safe though, I included an extra option to exit after a given number of seconds so it can measure the speed of your loop.
Sub RunInfinateForLoop(maxSeconds As Integer)
' Attempts to run a For loop to infinity but also exits if maxSeconds seconds have elapsed.
Dim t As Date = Now
Dim exitTime As Date = t.AddSeconds(maxSeconds)
Dim dCounter As Double
Dim strMessage As String
For dCounter = 1 To Double.PositiveInfinity
If Now >= exitTime Then Exit For
Next
strMessage = "Loop ended after " & dCounter.ToString & " loops in " & maxSeconds & " seconds." & vbCrLf &
"Average speed is " & CStr(dCounter / maxSeconds) & " loops per second."
MsgBox(strMessage, MsgBoxStyle.OkOnly, "Infinity Timer")
End Sub
What I do is add a timer then I change the interval to 1 and then I make it enabled then If I want it to constantly check something through the loop I just double click the timer for the timer_tick event then I type what I want. I usually use this for updating the settings if I want it to save every thing.