Display check box selections in one string (Visual Basic) - vb.net

Trying to get the results of all selected items to display in one message box string. I have this so far, which I know is wrong. If it matters, this list is filled via a text file and objects.
Dim cBike As String = "
For Each cBike In clbBikes.Items
cBike = clbBikes.SelectedItem & ", "
Next
MsgBox(("Your selection of: " & cBike))
Help please, my lecturer is taking forever and helping those who need it more.

You probably meant CheckedItems:
Dim cBike As String = ""
For Each chk As String In clbBikes.CheckedItems
cBike &= chk & ", "
Next
MessageBox.Show("Your selection of: " & cBike)

You need to actually concatenate the strings:
For Each cBike In clbBikes.Items
cBike = cBike + clbBikes.SelectedItem & ", "
Next
You need to then also remove the last comma
If (xml.Length > 2) Then
cBike = cBike.Remove(cBike.Length - 2, 2)
End If

Related

Split text in all lines inside of a string

Originally the Keywords will we pulled out from a text file located on a web server.
Dim KeyWords As String = Split(Split(TempSMTPFile, "# Keywords #")(1), "# Keywords #")(0)
I want to create a function that will split out all the keywords inside a string
The keywords in this example will be:
' This list might be changed to more or less keywords.
Dim KeyWords As String = "[One=Test1]" & vbNewLine & "[Two=Test2]" & vbNewLine & "[Three=Test3]"
' I Need a function to split out all keywords and do below check between all splits.
If KeyWords.ToLower.Contains("[" & Splited_keyword & "=") Then ' One, Two, Three
MsgBox(Split(Split(KeyWords, "[" & Splited_keyword & "=")(1), "]")(0)) ' Test1, Test2, Test3
End If
' This should print OneTest1, TwoTest2, ThreeTest3
Thanks for your comments, I was able to solve this with this solution.
Dim str As String() = keywords.Split(New [Char]() {CChar(vbCrLf)})
For Each s As String In str
If s.Contains("[") Then
Dim SplittedKeyword = Split(Split(s, "[")(1), "=")(0)
If TextUserShortDescription.Text.ToLower.Contains(SplittedKeyword.ToLower) Then
MsgBox(SplittedKeyword & (Split(Split(s, "[" & SplittedKeyword & "=")(1), "]")(0)))
End If
End If
Next
This could help you (untested):
Dim keyValues as String()
keyValues = KeyWords.Split(Environment.NewLine)
For Each (keyvalue as string in keyValues)
MsgBox(keyvalue.SubString(1, keyvalue.IndexOf("["c) + " " + keyvalue.SubString(keyvalue.IndexOf("="c), keyvalue.LastIndexOf("]"c)
End For

Substring a stringRaw from String1 to String2

If you didn't really get it what I actually want let me explain you better:
I have a:
stringRaw = "<img src=\"http://www.b92.net/news/pics/2015/01/15/111348233854b817af5b4bc991063053_v4 big.jpg\" title=\"\" alt=\"\" />"
Now I have to do some kind of substring from string1 = "<img src=\"" to string2 = "\" title=\"\" alt=\"\" />" and have to take what is in the middle of that which will be stringFinal = "http://www.b92.net/news/pics/2015/01/15/111348233854b817af5b4bc991063053_v4 big.jpg" in this case.
I can't use substring method since I never know how many characters can be in string1 and string2 also, seems like split method do not work as it should from THIS question on StackOverFlow.
edit For some reason my stringRaw has this value: vbCrLf & vbTab & vbTab & vbTab & "<img src=""http://www.b92.net/news/pics/2015/02/05/203819435354d39f17d74f0173575440_v4 big.jpg"" title="""" alt="""" />" & vbTab & vbTab
Anyway, I do what others advised and still I get an error that Index is out of range
Thank you for the answers in advance.
I was having issues going after the same characters so I went after text within the string such as "http" and "title=". Here it is in VB:
Dim startIndex As Int32 = stringRaw.IndexOf("http")
Dim endIndex As Int32 = stringRaw.IndexOf("title=") - 2
Return stringRaw.Substring(startIndex, endIndex - startIndex)
I used "http" and didn't include "://" just in case you need to get an "https" at some point. I used "title=" instead of "title" in case the word title ever showed up in the link.
I believe this code should grab the 'stringFinal' you desire.
// Get the index of 'src="'
Int32 startIndex = stringRaw.IndexOf("src=\"");
// Get the substring starting at 'src="' and ending at the first '"' after 'src="'.
stringRaw.Substring(startIndex, stringRaw.IndexOf("\"", startIndex) - startIndex);
Oh, sorry just noticed the VB tag. This is C# so the sytnax might be slightly different, but the functions and parameters should still be the same.
I forgot the - startIndex I was thinking that SubString second parameter was an index instead of count. Try adding that adjustment.
You could also use a regular expression. Something like:
Dim stringRaw as String = vbCrLf & vbTab & vbTab & vbTab & "<img src=""http://www.b92.net/news/pics/2015/02/05/203819435354d39f17d74f0173575440_v4 big.jpg"" title="""" alt="""" />" & vbTab & vbTab
Dim regx as New Regex("src=\""(.*)\""\s+title")
Dim match as Match = regx.Match(stringRaw)
If match.Success
' Outputs http://www.b92.net/news/pics/2015/02/05/203819435354d39f17d74f0173575440_v4 big.jpg
Console.WriteLine(match.Groups(1).Value)
End If
Public Function ExtractSrcAttribute(ByVal element As String) As String
Dim startToken As String = "src="""
Dim endToken As String = """"
Dim startIndex As Integer = element.IndexOf(startToken) + startToken.Length
Dim endIndex As Integer = element.IndexOf(endToken, startIndex)
If startIndex > element.Length OrElse endIndex > element.Length OrElse endIndex < startIndex Then
'error
End If
Return element.SubString(startIndex, endIndex)
End Function
As mentioned in my comment about you could use Regex to accomplish this easily. This uses a Positive-LookBehind and Positive-LookAhead. Please see below for example. This is tried and tested as well.
Dim rgex As New Regex("((?<=src=\\"").*)(?=\\""\s+title=)")
Dim mtch As Match = rgex.Match(TextBox1.Text)
If mtch.Success Then
MessageBox.Show(mtch.Groups(1).Value)
End If

VB.net string join, adds unneeded space

Having some issues in vb.net string to join two strings together for output to a txt document. My text document is getting an extra space between the two strings I join. This should not be happening.
If System.IO.File.Exists(path) = True Then
' Create a file to write to.
Dim sw As StreamWriter = System.IO.File.CreateText(path)
sw.WriteLine("Attribute VB_Name = " & Chr(34) & "KbTest" & Chr(34))
sw.WriteLine("")
sw.WriteLine("Public Sub DoKbTest()")
sw.WriteLine("'code here")
sw.WriteLine("Dim catia")
sw.WriteLine("set catia = GetObject(, " & Chr(34) & "CATIA.Application" & Chr(34) & ")")
sw.WriteLine("Dim partDocument1")
sw.WriteLine("Set partDocument1 = catia.ActiveDocument")
sw.WriteLine("Dim part1")
sw.WriteLine("Set part1 = partDocument1.Part")
sw.WriteLine("Dim hybridShapeFactory1")
sw.WriteLine("Set hybridShapeFactory1 = part1.HybridShapeFactory")
sw.WriteLine("Dim hybridShapeDirection1")
sw.WriteLine("Set hybridShapeDirection1 = hybridShapeFactory1.AddNewDirectionByCoord(1#, 2#, 3#)")
sw.WriteLine("Dim hybridBodies1")
sw.WriteLine("Set hybridBodies1 = part1.HybridBodies")
sw.WriteLine("Dim hybridBody1")
sw.WriteLine("Set hybridBody1 = hybridBodies1.Item(" & Chr(34) & "PointSetx" & Chr(34) & ")")
sw.WriteLine("dim skteches1")
sw.WriteLine("Set sketches1 = hybridBody1.HybridSketches")
sw.WriteLine("Dim sketch1")
sw.WriteLine("Set sketch1 = sketches1.Item(" & Chr(34) & "Sketch.1" & Chr(34) & ")")
sw.WriteLine("Dim reference1")
sw.WriteLine("Set reference1 = part1.CreateReferenceFromObject(sketch1)")
sw.WriteLine("Dim hybridShapeExtremum1")
sw.WriteLine("Set hybridShapeExtremum1 = hybridShapeFactory1.AddNewExtremum(reference1, hybridShapeDirection1, 1)")
sw.WriteLine("hybridBody1.AppendHybridShape hybridShapeExtremum1")
sw.WriteLine("Dim reference2")
Dim lessOneCount As String
Dim spacing As Double = 0
Dim count As String
Dim setString As String
'loop
THIS IS THE PART OF THE CODE THAT IS ADDING EXTRA SPACES
For i = 1 To numbOfPoints Step 1
count = Str(i)
count.Replace(" ", "")
MsgBox(count)
If i < 2 Then
lessOneCount = "hybridShapeExtremum1"
Else
lessOneCount = "HybridShapePointOnCurve" + Str(i - 1)
End If
sw.WriteLine("reference2 = part1.CreateReferenceFromObject(" + lessOneCount + ")")
setString = "Dim hybridShapePointOnCurve" + count
sw.WriteLine(setString)
setString = "hybridShapePointOnCurve" + count + " = hybridShapeFactory1.AddNewPointOnCurveWithReferenceFromDistance(reference1, reference2, spacing, False)"
sw.WriteLine(setString)
setString = "hybridShapePointOnCurve" + count + ".DistanceType = 1"
sw.WriteLine(setString)
setString = "hybridBody1.AppendHybridShape(hybridShapePointOnCurve" + count + ")"
sw.WriteLine(setString)
Next
sw.WriteLine("End Sub")
sw.Flush()
sw.Close()
End If
Sample output:
Dim hybridShapePointOnCurve 2
SHOULD be:
Dim hybridShapePointOnCurve2
What modifications should I make to the way I join strings?
Thanks!
Realized my comment didn't answer your question completely, so a few things:
The String.Replace method doesn't work like you think it does. Saying count.Replace(" ", "") doesn't actually change the variable count; the function actually returns a new string. For it work like you want, you would need to do count = count.Replace(" ", "").
Consider using a StringBuilder instead of concatenating a bunch of strings together. It will greatly improve performance. When using the StringBuilder class, you also wouldn't need to write to the StreamWriter until the very end, simply by calling sw.Write(stringBuilderObject.ToString())
I haven't used VB.NET in a while, but I would check what Str(i) returns. Instead of using VB functions, consider using .NET functions by saying count = i.ToString(). According to Sky, the Str function indeed returns a space because it reserves it for the negative sign. Based on this, I would use the .ToString() method instead.
I spoke to quickly in my comment, the Str function reserves room for the sign, since it is a positive number there is no sign, if it was negative there would be a minus sign there. Try Trim(Str(i)) instead
From above link(emphasis mine):
This example uses the Str function to return a String representation of a number. When a positive number is converted to a string, a leading space is always reserved for its sign.

Prevent the `vbLf` being included in a `String.Length` calculation

I have a Collection of servers which I take from a multiline textbox.
I have some simple validation which should be trimming whitespace (to prevent an entry being created for blank line), but it's not working.
For example, if Me.formServers.txtServers.Text is as follows, the lengths of the lines are returned as 5, 5, 5 and 4. How can I correctly calculate the length of each line and thus avoid erroneous items being added to my Collection? Thanks.
TTSA
TTSB
TTSC
TTSD
Here is my code
Me.Servers = New Collection ' Reset 'Servers' to ensure only the correct servers are included
For Each Server As String In Me.formServers.txtServers.Text.Split(vbLf)
If Not Server.Trim.Length = 0 Then Me.Servers.Add(Server)
MsgBox(Server.Length)
Next
This test was interesting:
Dim s As String = "TTSA" & vbCrLf
s &= "TTSB" & vbLf
s &= "TTSC" & vbCr
s &= "TTSD" & Environment.NewLine
s &= "TTSE" & vbNewLine
Dim Excluded() As String
Excluded = s.Split({vbCrLf, vbLf}, StringSplitOptions.None)
For Each s In Excluded
Debug.Print(s & " " & s.Length)
Next
result:
TTSA 4
TTSB 4
TTSC ' vbCr was not in list so is still in the string
TTSD 9
TTSE 4
0 ' last separator honored
Corrected to:
Excluded = s.Split({vbCrLf, vbLf, vbCr}, _
StringSplitOptions.RemoveEmptyEntries)

Get Text between characters in a string

I have a text file with a list of music that looks like this:
BeginSong{
Song Name
Artist
Genre
}EndSong
There are multiple instances of this.
I'm wanting to get the text between the BeginSong{ and }EndSong and put the song info
into a string array. Then I want to add each instance to a ListBox as Artist - Song Name
(that part I'm sure I can figure out though). I hope that was a clear description.
Use the ReadLine() function of the FileStream
since you already know the order of the information, you should be able to loop all File Lines and store them in their corresponding properties.
Pseudo:
WHILE Reader.Read()
Store Line in BeginSongTextVariable
Read Next Line
Store Line in SongNameVariable
Read Next Line
Store Line in ArtistNameVariable
Read Next Line
Store Line in GenreVariable
Read Next Line
Store Line in EndSongTextVariable
Add The Above Variables in List
End While
You can use a regular expression with named groups:
BeginSong{\n(?<song_name>.*)\n(?<artist>.*)\n(?<genre>.*)\n}EndSong
Something like this:
Imports System.Text.RegularExpressions
'...
Dim s As New Regex("BeginSong{\n(?<song_name>.*)\n(?<artist>.*)\n(?<genre>.*)\n}EndSong")
Dim mc As MatchCollection = s.Matches(inputFile)
For Each m As Match In mc
Dim song_name As String = m.Groups("song_name").Value
Dim artist As String = m.Groups("artist").Value
Dim genre As String = m.Groups("genre").Value
'use or store these values as planned
Next
There is a nice answer from Neolisk that uses Regular Expressions. But since you also included the VB6 tag in addition to VB.NET, I'll take a shot at a VB6 solution.
You can use the string Split function, and split on the "ends", i.e. "BeginSong{" and "}EndSong"
Dim songInfos As String
Dim firstArray() As String
Dim secondArray() As String
Dim thirdArray() As String
Dim songInfoArray() As String
Dim i As Integer
Dim songCounter As Integer
' to test:
songInfos = songInfos & "BeginSong{" & vbNewLine
songInfos = songInfos & "Song Name1" & vbNewLine
songInfos = songInfos & "Artist1" & vbNewLine
songInfos = songInfos & "Genre1" & vbNewLine
songInfos = songInfos & "}EndSong" & vbNewLine
songInfos = songInfos & "BeginSong{" & vbNewLine
songInfos = songInfos & "Song Name2" & vbNewLine
songInfos = songInfos & "Artist2" & vbNewLine
songInfos = songInfos & "Genre2" & vbNewLine
songInfos = songInfos & "}EndSong"
firstArray = Split(songInfos, "BeginSong{")
songCounter = 0
ReDim songInfoArray(2, 0)
For i = 1 To UBound(firstArray) Step 1
secondArray = Split(firstArray(i), "}EndSong")
thirdArray = Split(secondArray(0), vbNewLine)
songInfoArray(0, songCounter) = thirdArray(1)
songInfoArray(1, songCounter) = thirdArray(2)
songInfoArray(2, songCounter) = thirdArray(3)
songCounter = songCounter + 1
If i < UBound(firstArray) Then
ReDim Preserve songInfoArray(2, songCounter)
End If
Next i
The watch after the last line. Note the structure of songInfoArray, which was required for it to be ReDimmed