Bali C
Bali C

Reputation: 31251

C# Win Forms Save Controls

I have made a Win Form and have a few controls like checkboxes, radio buttons etc. What I hope to happen is that the user will choose some settings e.g. tick the box to start the program on startup, then they can quit, when they open it again, how do I ensure that the choices that they made are saved? Thanks.

Upvotes: 2

Views: 1809

Answers (3)

ispiro
ispiro

Reputation: 27723

Perhaps you’re looking for something like this:

Add this:

using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

Then this to the program:

    for_save info = new for_save();
    string general_path = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
    string path = general_path + "\\MyApplication";
    BinaryFormatter serializer = new BinaryFormatter();

    info.check = true;
    info.radio = false;            

    //write
    Directory.CreateDirectory(path);
    Stream write_stream = File.Create(path + "\\MyFile.txt");
    serializer.Serialize(write_stream, info);
    write_stream.Close();

    //read
    Stream read_stream = File.OpenRead(path + "\\MyFile.txt");
    for_save read_info = (for_save) serializer.Deserialize(read_stream);
    read_stream.Close();

    textBox1.Text = read_info.check.ToString() + read_info.radio.ToString();

And this class:

[Serializable()]
class for_save
{
    public bool check;
    public bool radio;
}

Upvotes: 2

Iain Ward
Iain Ward

Reputation: 9946

There are a few ways, but I'd recommend using the .NET user settings method to save their settings in the properties section of the application and reload and set them when they start the application again.

Here's an example:

Save Setting

Properties.Settings.Default.CheckboxChecked = true;
Properties.Settings.Default.Save();

Load Setting

checkBox.Checked = Properties.Settings.Default.CheckboxChecked;

I'd recommend giving them more meaningful names, however.

You can read more, with examples here: MSDN Using Application Settings and User Settings

This is also a nice tutorial on how to implement user settings from start to finish: C# - Saving User Settings - Easy way!

Upvotes: 4

Rosmarine Popcorn
Rosmarine Popcorn

Reputation: 10965

http://msdn.microsoft.com/en-us/library/aa730869%28v=vs.80%29.aspx Here is and Article how to use Settings in C# Application .

Where you can check ,if CheckBox is Checked with a Boolean etc.

Upvotes: 2

Related Questions