By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
448,538 Members | 911 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 448,538 IT Pros & Developers. It's quick & easy.

I need help with writing the code to save multiple variables to a text file...

P: 2
I want to allow users of my program to click File>Save and have a save dialog open and allow them to save all of their input. here is the background of my program.

I have a program that allows students to calculate their grades as the class progresses. I want them to be able to type in their information and i already have the program written for them to be able to calculate everything via different types of work based on weights for homework tests etc etc.

I do not know how to write the code to allow variables to be saved to a text file defined by the user.

I also do not know how to write the code to allow that user to open that file and import all the data back into it.

If someone could write me sample code, based on saving these three variables i would greatly appreciate it.

variables hwPtsPoss (homework points possible), hwPtsAtt (homework points attained), and.... hwWeight (homework weight) all of these are defined as variable type double and standardly use digits and decimals only.

Thank you very much in advance to whomever can help.
Feb 8 '08 #1
Share this Question
Share on Google+
1 Reply

Expert 100+
P: 979
Hi Josh,

The following code is a simple way to create a text file and add some text to it. Hopefully you can see how easy it would be to adapt this for your own uses.

The last bit with the OpenFileDialog is the bit that you can use to select an existing file and append text to it. The AppendAllText method will open the specified file, add the desired text to the end of the file and then close it. You can use the OpenFileDialog to display the contents of a text file in a rich text box or similar as well.

First you need to import the IO namespace.

Expand|Select|Wrap|Line Numbers
  1.  Imports System.IO
Then the code:

Expand|Select|Wrap|Line Numbers
  3. Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
  6. Dim fp As StreamWriter
  7. Dim sText As String = ""
  9. Try
  12. fp = File.CreateText("C:\test.txt")
  15. sText += hwPtsAtt.ToString
  16. sText += " out of "
  17. sText += hwPtsPoss.ToString
  18. sText += " with a weighting of "
  19. sText += hwWeight.ToString
  22. fp.WriteLine(sText)
  25. fp.Close()
  27. Catch ex As Exception
  28. End Try
  30. OpenFileDialog1.ShowDialog()
  32. File.AppendAllText(OpenFileDialog1.FileName, "HELLO WORLD")
  35. End Sub
Have a play around with it and let me know how you get on,

Dr B
Feb 8 '08 #2

Post your reply

Sign in to post your reply or Sign up for a free account.