Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Recursive string creation

Status
Not open for further replies.

barrykellett

Programmer
Mar 4, 2003
29
GB
Hi, I have the following simple piece of code:

For Each Item In ListBox1.Items
If Item.Selected Then
Stuff = Stuff & "," & Item.Text
End If

Next

This Will create me a String of email addresses seperated by "," however as it is now i get a "," before the first address which i dont want. How can i get round this? I am sure it is very logical but I cant think how!!
Thanks
 
try this:
stuff = Item.Text
Stuff = Stuff & "," & Item.Text
 
I had tried this, but if i place both lines inside the loop it produces addresses twice
 
when your for is done
For
...
Next
Stuff = Stuff.Remove(0, 1)
hth,
Marty
 
Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

Line 34:
Line 35: Next
Line 36: Stuff = Stuff.Remove(0,1)
Line 37: If Stuff <> "" Then
Line 38: Label1.Text = "<b>You chose :</b> <br>" & Stuff

:(
 
For Each Item In ListBox1.Items
If Item.Selected Then
if stuff = string.empty then
Stuff = Item.Text
else
Stuff = Stuff & "," & Item.Text
end if
End If
Next

You should be using a System.Text.StringBuilder to do this. Use Stringbuilder.Append(). Concatenating strings is very bad practice.
 
Better yet. Use a StringBuilder. It saves on garbage collection on all those intermediate strings.
Dim sb as New System.Text.Stringbuilder(100)
For Each Item In ListBox1.Items
If Item.Selected Then
if sb.Length > 0 then
sb.Append(",")
end if
sb.append(Item.Text)
End if
Next
Stuff = sb.tostring
' Now only sb as to "Garbage Collected"

The concatenation that you had is "murder" on storage and causes Garbage Collection of many separate string objects.
Stuff = Stuff & Item.text does not replace or immediately free the storeage for the previous contents of stuff.
Say each line is 5 characters.
5 * (10 * 10 + 10) / 2 = 275 characters allocated .

It may not seem like much but it builds up after you write all your programs like that and they all run at the same time.

Forms/Controls Resizing/Tabbing
Compare Code
Generate Sort Class in VB
Check To MS)
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top