Qbasicnews.com

Full Version: saving in vb
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
can anyone tell me how to save info inside a textbox in vb using the common dialog control?
Everything is in the msdn: http://msdn.microsoft.com
try something like this...it's a little archaic but it's a nice quick fix:

Code:
Sub SaveFile (ByVal filename As String)
On Local Error Resume Next
Dim fh As Integer
'dlg is the name of the common dialog control on your form
'txtText is the name of the textbox
dlg.CancelError = True
dlg.Filename = ""
dlg.Filter = "Text Files (*.txt)|*.txt|All Files (*.*)|*.*|"
dlg.DialogTitle = "Save File as..."
dlg.ShowSave
If Err Then Exit Sub
fh = FreeFile
Open dlg.Filename For Output As #fh
Print #fh, txtText.Text
Close fh
End Sub
I typed this from memory, so it may be slightly inaccurate, and I didn't use any real code format shortcuts (like With).
Code:
Private Sub open_Click()
With dlgCmnDlg
    .DialogTitle = "Open file"
    .Filter = "Text Files (*.txt)|*.txt"
    .ShowOpen
    If .filename = "" Then Exit Sub
    txtEditor.Text = OpenFile(.filename)
End With
End Sub

Private Sub save_Click()
With dlgCmnDlg
    .DialogTitle = "Save File"
    .Filter = "Text files(*.txt)|*.txt"
    .ShowSave
    If .filename = "" Then Exit Sub
    SaveFile(.filename, txtEditor.Text) = .filename
      
    End With
End Sub

Public Function SaveFile(filename, Text)
On Error GoTo errhndl
Open filename For Output As #1
Print #1, Text
Close #1
Exit Function
errhndl:
' There was an error - the file is probably read-only
MsgBox "Error saving file: " & Err.Description & " - Check that the file is not marked as read-only and that you have permission to write to the file.", vbOKOnly + vbCritical, "Error!"
End Function

Public Function OpenFile(filename)
Open filename For Input As #1
OpenFile = Input(LOF(1), 1)
Close #1
End Function
some of my routines you might want to look at...
For a better solution you may want to look up Rich text box. It has built in saving/loading features. And you can even format text inside it.
Mech: change the scope of your error trap. Smile You should really specify it as Local when trying to catch a local error. And get rid of the #1 dude...static file handles are a no-no. Big Grin For your MsgBox, you're better off using Or rather than + when combining MsgBox flags. Smile
Does FREEFILE still exist in vb?
Of course :p or else I wouldn't have used it in my example Wink
Oops! I missed it =P.