Click here to Skip to main content
15,887,214 members
Please Sign up or sign in to vote.
3.00/5 (1 vote)
See more:
I have tried using the code below, the logic behind it seems to be fine but it does not seem to work once I run the code,it highlights "MyString" and says " variable is used before it has been assigned a value" has anyone got suggestions?Thank you in advance.

What I have tried:

If ListBox1.SelectedItems.Count > 0 Then
           ListBox1.Items.RemoveAt(ListBox1.SelectedIndex)
           Dim MyString As String
           For Count As Integer = 0 To ListBox1.Items.Count - 1
               MyString &= ListBox1.Items.Item(Count) & Environment.NewLine
           Next
           My.Computer.FileSystem.WriteAllText("Z:\Desktop\ciao.txt", MyString, False)
       End If
   End Sub
Posted
Updated 15-Feb-18 4:53am
v3

1 solution

As the error message says, you are reading the value of the variable MyString before the first assignment to it.

Firstly, if there are no items left in ListBox1, the code inside your loop will never execute. When you come to the WriteAllText line, the variable has not had a value assigned to it.

Secondly, inside the loop, you're appending a string to the variable. But that involves reading the current value of the variable first. On the first iteration of the loop, no value has been assigned.

The quick fix is to assign a value before the loop:
VB.NET
Dim MyString As String = ""

However, it's generally a good idea to avoid string concatenation in a loop. Depending on the number of items in your list, you might want to loop at using a StringBuilder[^] to build the string.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900