3

I need to know if is possible to save the state of a CheckBox in C#? I mean if I check the CheckBox and close the program, once I restart the program the CheckBox will still stay checked. Is it possible to?

Samuel Slade
  • 8,405
  • 6
  • 33
  • 55
Derezzed
  • 1,093
  • 3
  • 11
  • 15
  • You need to store the value of the checkbox somewhere and read it again when the program runs. It won't happen by itself. – LarsTech Jan 23 '12 at 16:12
  • Well,you can save it in a XML file or app.config or equivalent. – The Mask Jan 23 '12 at 16:12
  • @LarsTech: I admit that more then one time I thought about lack of this kind of feature in WinForms (especially on complex UI) where you can mark UI element with a attribute and it automaticaly store and load it's state. – Tigran Jan 23 '12 at 16:14
  • You can also save the Checked State to the .config file or .INI File or Text File the Registry is not the only place – MethodMan Jan 23 '12 at 16:16
  • Google [winforms database programming tutorial c#](http://www.google.com/search?q=winforms+database+programming+tutorial+c%23) – Olivier Jacot-Descombes Jan 23 '12 at 16:17
  • Yes I tried using an XML, the problem is that when my checkbox is checked it writes & saves the statement, so when the program starts, it reads the XML and make the Checked Statement true so it will saves again and the app will crash because the file will be in used. – Derezzed Jan 23 '12 at 16:55

7 Answers7

3

This is rather a general question. You need to serialise the state yourself somehow, but how, and where to depends on a lot of things.

Possibly take a look at a Settings file for a simple start.

GazTheDestroyer
  • 20,722
  • 9
  • 70
  • 103
1

For this, you will need to record the state of the CheckBox yourself. For example, you could store the value in an XML document that would contain your application's UI states. An example, in a very simplistic form, you could do the following:

// ... as the application is closing ...
// Store the state of the check box
System.IO.File.WriteAllText(@"C:\AppFile.txt", this.CheckBox1.IsChecked.ToString());

// ...

// ... as the application is being initialized ...
// Read the state of the check box
string value = System.IO.File.ReadAllText(@"C:\AppFile.txt");
this.CheckBox1.IsChecked = bool.Parse(value);

As you can see, this simply stores the value in a file and reads it back in during initialization. This is not a great way of doing it, but it demonstrates a possible process to follow.

Samuel Slade
  • 8,405
  • 6
  • 33
  • 55
1

The easiest way of doing this would be to use a config XML file. You can add this very easily through visual studio, there is no need to use registry and it can be used if the app is portable as the settings are saved with the program. A tutorial of how to set this up is here:

http://www.sorrowman.org/c-sharp-programmer/save-user-settings.html

Bali C
  • 30,582
  • 35
  • 123
  • 152
0

I would use Settings like this:

Assuming a boolean setting called boxChecked has been created.

//if user checks box
Properties.Settings.Default.boxChecked = true;
Properties.Settings.Default.Save();

//...

//when the program loads
if(Properties.Settings.Default.boxChecked)
{
    checkBox1.Checked = true;
}
else
{
    checkBox1.Checked = false;
}

Jay Brown
  • 139
  • 2
  • 13
0

If you are using Web application cookie enabled and storing the information in cookie then it is possible.

You can checkout http://www.daniweb.com/web-development/aspnet/threads/30505

http://asp.net-tutorials.com/state/cookies/

Ravi Vanapalli
  • 9,805
  • 3
  • 33
  • 43
0

In C# you can use the Settings file. Information how to use it can be found here : http://msdn.microsoft.com/en-us/library/aa730869%28v=vs.80%29.aspx

RvdK
  • 19,580
  • 4
  • 64
  • 107
0

If you wanted to save this to the Registry you could do something like this

RegistryKey Regkey = "HKEY_CURRENT_USER\\Software\\MyApplication";
RegKey.SetValue("Checkbox", Checkbox.Checked);

but personally I would save it to the .Config file

Here is an example of how to do it using the Config File if you so desire

private static string getConfigFilePath()
{
    return Assembly.GetExecutingAssembly().Location + ".config";
}
private static XmlDocument loadConfigDocument()
{
    XmlDocument docx = null;
    try
    {
        docx = new XmlDocument();
        docx.Load(getConfigFilePath());
        return docx;
    }
    catch (System.IO.FileNotFoundException e)
    {
        throw new Exception("No configuration file found.", e);
    }
}
private void rem_CheckedChanged(object sender, EventArgs e)
{
    if (rem.Checked == true)
    {
        rem.CheckState = CheckState.Checked;
        System.Xml.XmlDocument docx = new System.Xml.XmlDocument();
        docx = loadConfigDocument();
        System.Xml.XmlNode node;
        node = docx.SelectSingleNode("//appsettings");
        try
        {
            string key = "rem.checked";
            string value = "true";
            XmlElement elem = (XmlElement)node.SelectSingleNode(string.Format("//add[@key='{0}']", key));
            if (elem != null)
            {
                elem.SetAttribute("value", value);
            }
            else
            {
               elem = docx.CreateElement("add");
                elem.SetAttribute("key", key);
                elem.SetAttribute("value", value);
                node.AppendChild(elem);
            }
            docx.Save(getConfigFilePath());
        }
        catch (Exception e2)
        {
            MessageBox.Show(e2.Message);
        }
    }   
}           
MethodMan
  • 18,625
  • 6
  • 34
  • 52
  • 1
    I'd personally avoid the registry unless no other options are available to avoid pollution. His app would also require sufficient privileges. So yes .config is the better option. – Jeb Jan 23 '12 at 16:39