hannir hannir - 5 months ago 19
Vb.net Question

How to pass ListBox selected item into file?

What I have:

Private Sub ChooseProgram_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ChooseProgram.SelectedIndexChanged

Dim curItem As String = ChooseProgram.SelectedItem.ToString()

End Sub

Private Sub Install_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Install.Click

Dim jhin As System.IO.StreamWriter
jhin = My.Computer.FileSystem.OpenTextFileWriter("C:\Temp\jhin.bat", True)

jhin.WriteLine("$program = " & curitem.string")
jhin.Close()
End Sub


I just want to write the string into the file.
How is that possible?

Thx for ur help!
Hannir

UPDATE:

' Ensure an item is selected
If ChooseProgram.SelectedItem Is Not Nothing Then
curItem = ChooseProgram.SelectedItem.ToString()
End If


I get an error here.

"The Is operator does not accept operands of type " integer " . The operands must be reference types, or permit types , NULL values ​​."

Really thx for ur quick help! @Pro Grammer

Answer

For starters you have to move the declaration of the curItem variable out of the SelectedIndexChanged method, to what's called Class level.

As it stands your variable is accessible within your SelectedIndexChanged method only, whereas if you move it to class level it will be accessible by everything within that class (the class in this case is your Form). You then just modify the variable from your SelectedIndexChanged method.

Dim curItem As String = "" 'We'll start with an empty string.

Private Sub ChooseProgram_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ChooseProgram.SelectedIndexChanged

    curItem = ChooseProgram.SelectedItem.ToString()

End Sub

Now you will be able to access the variable from your button and write it to a file.

The last thing you have to do is to close the StreamWriter that you create so that it will release the lock on the file. The easiest and best way to do so is wrapping it in an Using/End Using block.

Private Sub Install_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Install.Click

    Using jhin As System.IO.StreamWriter = My.Computer.FileSystem.OpenTextFileWriter("C:\Temp\jhin.bat", True)

        jhin.WriteLine("$program = " & curItem)

    End Using
End Sub