Click here to Skip to main content
15,887,453 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I need help in saving contents from a listbox and when you click a save button, you can save what is in the listbox into a .txt file.

I need to do this for a project and i would really like some help on how to do this.

This is what I had, and when i tried to open it, it wouldn't work:

VB
Dim sNewName As String
CommonDialog1.DialogTitle = "Enter Name To Save File As"
CommonDialog1.Filter = "Text File (*.txt)  |  *.txt"
CommonDialog1.ShowSave
sNewName = CommonDialog1.filename
MsgBox sNewName
If sNewName <> "" Then
    Open sNewName For Output As #1
    Print #1,
    Close #1
    sFileName = sNewName
End If


this is the code that i had for opening the items into the listbox:
VB
CommonDialog1.DialogTitle = "Enter Name Of File To Open"
CommonDialog1.Filter = "Txt Files (*.txt)  |  *.txt"
CommonDialog1.ShowOpen
sFileName = CommonDialog1.filename
If sFileName = "" Then Exit Sub
Open sFileName For Input As #1
For i = 1 To MAXLINES
    If EOF(1) Then Exit For
    Line Input #1, strline
    strline = Trim(strline)
    If Len(strline) <> 0 Then List1.AddItem strline
Next i
Close #1
lbl1count = List1.ListCount
cityname = InputBox("What is the Name of the City?", "Name of City")
lbl1city.Caption = cityname
Exit Sub


maybe this will help.
Posted
Updated 9-May-14 9:12am
v3
Comments
[no name] 9-May-14 15:00pm    
Okay so show us what you have tried, describe what the problem is with your code and we will see if we can help you.
DamithSL 9-May-14 15:08pm    
update the question with how you load items to listbox
[no name] 9-May-14 15:10pm    
Well you are missing a For loop to iterate through your listbox items and your Print statement is missing what it is that you want to save to your file.
CodeMaster9 9-May-14 15:12pm    
what do i put for the print statement, that is confusing me
[no name] 9-May-14 15:23pm    
Try List1.Items(i) or replace "i" with the variable that you use in your For loop.

1 solution

You need to loop through the collection of ListBox items.
VB
Open ... AS #1
For i = 0 to ListBox1.ListCount -1
    Print #1, ListBox1.List(i)
Next i
Close #1
 
Share this answer
 
Comments
[no name] 9-May-14 15:38pm    
Why Maciej, you wrote VB6 code! Going over to the Dark Side? :-)
Maciej Los 9-May-14 15:44pm    
I'm not Vader ;)
[no name] 9-May-14 15:46pm    
I don't know... Maciej Vader has a nice ring to it... :-) Or would it be Darth Maciej? lol 5 anyway.
Maciej Los 9-May-14 15:51pm    
Thank you, Wes ;)
joshrduncan2012 9-May-14 16:22pm    
Nice Maciej! :) My +5 too!

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