none
save checkbox state to settings file RRS feed

  • Question

  • i already have settings file create with 3 bool vars scoope user named skype_mute and skype_vol_down....

    and i need to save the 3 checkbox states to the settings file the

    i have a lkistcheckbox with 3 checkboxes and the frist is independent and the second and 3rd is if 2 is maked 3rd is unmarked and vice versa how to save the values to the settings file.

     

    previously i use normal checkbox and to save i just use:

    //in preferences form 3
    save button // should save all 3 checkboxes state however this is for normal checkbox and not list checkbox
     private void btn_guardar_pref_Click(object sender, EventArgs e)
            {
                Settings1 set = new Settings1();
                set.cb_MinTarefas = checkBox1.Checked;
                set.Save();
                this.Close();
            }
    
    // check checkbox state before opening form
    
     public partial class Form3 : Form
        {
            public Form3()
            {
                InitializeComponent();
                Settings1 set = new Settings1();
                checkBox1.Checked = set.cb_MinTarefas ;
    
    
    // new code to checkbox list 3 checkboxes frist is independent and 2nd and 3rd is just allow select or 3rd or 2nd
    
      private void checkedListBox1_ItemCheck(object sender, ItemCheckEventArgs e)
            {
                
                    CheckedListBox.CheckedIndexCollection checkedIndices = checkedListBox1.CheckedIndices;
                    if (checkedIndices.Contains(0) && checkedIndices.Count == 2 && (int)e.NewValue == 1)
                    {
                        checkedListBox1.SetItemChecked((e.Index == 1 ? 2 : 1), false);
                    }
                    if (!checkedIndices.Contains(0) && checkedIndices.Count > 0 && (int)e.NewValue == 1)
                    {
                        checkedListBox1.SetItemChecked((e.Index == 1 ? 2 : 1), false);
                    }
                  
    //in form1 main form
                
    
             private void Form1_Load(object sender, EventArgs e)
            {
    
                VerificarActualizaçoesWebradio();
    
                Settings1 set = new Settings1();
                bool checkedValue = cb_MinTarefas ;
    
    so the checkbox names are 1- cb_MinTarefas 2nd is cb_BaixarVolSkype 3rd is cb_SkypeMute
    
    so how can i do this?
    

    Thursday, November 10, 2011 5:42 PM

All replies

  • > i need to save the 3 checkbox states to the settings file

     

    you can use databinding.
    below is an example with two approaches: v1 and v2.

     

    using System.Data;
    using System.IO;
    using System.Windows.Forms;
    using System.Xml.Linq;
    
    namespace WindowsFormsApplication3
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                var xml = @"<root>
                    <data checked='true' />
                </root>";
    
                // v1: load xml and binding to xelement
                var xe = XElement.Parse(xml);
                var cb1 = new CheckBox { Parent = this, Dock = DockStyle.Top, Text = "XElement" };
                cb1.DataBindings.Add("Checked", xe.Element("data").Attribute("checked"), "Value");
    
                // v2: load xml and binding to dataset
                var ds = new DataSet();
                ds.ReadXml(new StringReader(xml));
                var cb2 = new CheckBox { Parent = this, Dock = DockStyle.Top, Text = "DataSet" };
                cb2.DataBindings.Add("Checked", ds, "data.checked");
    
                // test
                this.Menu = new MainMenu();
                this.Menu.MenuItems.Add("trace", (s, e) => 
                {
                    foreach(Control c in this.Controls)
                        foreach(Binding b in c.DataBindings)
                            b.WriteValue();
    
                    // todo: save to file
                    MessageBox.Show("DataSet: " + ds.GetXml() + "\n\n XElement: " + xe);
                });
            }
        }
    }
    
    

    • Proposed as answer by Malobukv Thursday, November 10, 2011 8:07 PM
    Thursday, November 10, 2011 7:11 PM
  • so you suggest to use xml file instead of settings file ok i agree

    but i want to save xml results in the debug/bin folder

    and this example where is saving my 3 checkboxes

    wich is best to use v1 or v2?

    Thursday, November 10, 2011 7:16 PM
  • > i want to save xml results in the debug/bin folder and this example where is saving my 3 checkboxes wich is best to use v1 or v2?

     
    v1 is best way if you need to manage settings for users and maybe store a versions of settings and another information.
    below is an example, which loads information from file and saves file when form closing
     

    using System.Data;
    using System.IO;
    using System.Windows.Forms;
    using System.Xml.Linq;
    
    namespace WindowsFormsApplication3
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                var ds = new DataSet();
                var file = "settings.xml";
                if(File.Exists(file))
                    ds.ReadXml(file);
                else
                {
                    var dt = new DataTable("data");
                    dt.Columns.Add("MinTarefas", typeof(bool)).DefaultValue = true;
                    dt.Columns.Add("BaixarVolSkype", typeof(bool)).DefaultValue = true;
                    dt.Columns.Add("SkypeMute", typeof(bool)).DefaultValue = true;
                    ds.Tables.Add(dt);
                    dt.Rows.Add(true, true, true);
                }
                
                new CheckBox { Parent = this, Dock = DockStyle.Top, Text = "MinTarefas" }
                    .DataBindings.Add("Checked", ds, "data.MinTarefas");
                new CheckBox { Parent = this, Dock = DockStyle.Top, Text = "BaixarVolSkype" }
                    .DataBindings.Add("Checked", ds, "data.BaixarVolSkype");
                new CheckBox { Parent = this, Dock = DockStyle.Top, Text = "SkypeMute" }
                    .DataBindings.Add("Checked", ds, "data.SkypeMute");
    
                this.FormClosing += (s, e) => 
                {
                    foreach(Control c in this.Controls)
                        foreach(Binding b in c.DataBindings)
                            b.WriteValue();
    
                    ds.AcceptChanges();
                    ds.WriteXml(file);
                };
            }
        }
    }
    
    

    • Proposed as answer by Malobukv Thursday, November 10, 2011 8:07 PM
    Thursday, November 10, 2011 8:06 PM
  • thanks for you reply

    but please adapt you code to correspond with my similar code is frist post

    checkbox is ina checkboxlist wich into it have 3 checkboxes

    and this checkbox list is in form3 and when i lauch the app main form (form1) i need to check checkbox status in load event like i do in my frist post

    this is the way how i build the checkbox list.

    private void checkedListBox1_ItemCheck(object sender, ItemCheckEventArgs e)
            {
                
                    CheckedListBox.CheckedIndexCollection checkedIndices = checkedListBox1.CheckedIndices;
                    if (checkedIndices.Contains(0) && checkedIndices.Count == 2 && (int)e.NewValue == 1)
                    {
                        checkedListBox1.SetItemChecked((e.Index == 1 ? 2 : 1), false);
                    }
                    if (!checkedIndices.Contains(0) && checkedIndices.Count > 0 && (int)e.NewValue == 1)
                    {
                        checkedListBox1.SetItemChecked((e.Index == 1 ? 2 : 1), false);
                    }
                  
    
    

    here are 3 checkboxes the frist is indepedent from others 2nd and 3rd i just allow to mark os 2nd or 3rd

    names for checkboxes in form3

     1- cb_MinTarefas

     2nd is cb_BaixarVolSkype

    3rd is cb_SkypeMute

    soi need to check this values in form1_load and form3 after initialize component8see 1st post code example)

    also need to have the code how to check checkbox state to have a button save and exit when open form 3

    i think its easier to see the 1st post to see what i want and adapt ur code

    is this actually creating and saving the xml info on the debug/bin folder?

    if you see 1st post i use settings file but  prefer to use xml and saving the xml info and xml true/false results on it on debug/bin folder

    Thursday, November 10, 2011 8:24 PM
  • > please adapt you code to correspond with my similar code is frist post [...] 'i have a lkistcheckbox with 3 checkboxes and the frist is independent and the second and 3rd is if 2 is maked 3rd is unmarked and vice versa'

     
    if i understood correctly then try following
     
      
    using System.Data;
    using System.IO;
    using System.Windows.Forms;
    using System.Xml.Linq;
    using System;
    
    namespace WindowsFormsApplication3
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                var ds = new DataSet();
                var file = "settings.xml";
                if(File.Exists(file))
                    ds.ReadXml(file);
                else
                {
                    var dt = new DataTable("data");
                    dt.Columns.Add("MinTarefas", typeof(bool)).DefaultValue = true;
                    dt.Columns.Add("BaixarVolSkype", typeof(bool)).DefaultValue = true;
                    dt.Columns.Add("SkypeMute", typeof(bool)).DefaultValue = true;
                    ds.Tables.Add(dt);
                    dt.Rows.Add(true, true, true);
                }
                
                new CheckBox { Parent = this, Dock = DockStyle.Top, Text = "MinTarefas" }
                    .DataBindings.Add("Checked", ds, "data.MinTarefas");
    
                var cb2 = new CheckBox { Parent = this, Dock = DockStyle.Top, Text = "BaixarVolSkype" };
                cb2.DataBindings.Add("Checked", ds, "data.BaixarVolSkype");
                
                var cb3 = new CheckBox { Parent = this, Dock = DockStyle.Top, Text = "SkypeMute" };
                cb3.DataBindings.Add("Checked", ds, "data.SkypeMute");
    
                cb2.CheckedChanged += (s, e) => 
                {
                    if(cb2.CheckState == CheckState.Checked)
                        cb3.CheckState = CheckState.Unchecked;
                };
                
                cb3.CheckedChanged += (s, e) => 
                {
                    if(cb3.CheckState == CheckState.Checked)
                        cb2.CheckState = CheckState.Unchecked;
                };
    
                this.FormClosing += (s, e) => 
                {
                    foreach(Control c in this.Controls)
                        foreach(Binding b in c.DataBindings)
                            b.WriteValue();
    
                    ds.AcceptChanges();
                    ds.WriteXml(file);
                };
            }
        }
    }
    
    
    • Edited by Malobukv Thursday, November 10, 2011 9:38 PM
    • Proposed as answer by Malobukv Thursday, November 10, 2011 9:39 PM
    Thursday, November 10, 2011 9:38 PM
  • 1- i need to see checkbox state in some event of form1(main form), se if them are or not checked

    2- in  form 3[preferences form] wich is a new form with this checkboxes when the form opens ofcourse i need to see read from xml file the checkbox states and then is true check them if false not check them

    3- need to save the checkboxes state in a xml file in the project folder

    so withyour code i cant distinct if your are talking if its form3 or form 1 because i just see form1

    form 3  is the preferences formform1 should read checkbox state from the xml file!hope you have understand better

    Thursday, November 10, 2011 10:04 PM
  • > 3- need to save the checkboxes state in a xml file in the project folder

     

    if you run my code above, then you'll see settings.xml in folder \bin\Debug.
    you can change the settings path as you want. something like this:

    var file = @"..\..\settings.xml";
    - or - 
    var file = @"c:\temp\settings.xml";
    
    
    


    > so withyour code i cant distinct if your are talking if its form3 or form 1 because i just see form1
    form 3 is the preferences formform1 should read checkbox state from the xml file!



    do you need to have CheckBoxes in subform?
    am i understand you properly: form1 loads xml, and after some user action opens form3 with checkboxes?

     

    • Edited by Malobukv Friday, November 11, 2011 9:43 PM
    Thursday, November 10, 2011 10:19 PM
  • as  said  in previous post point 1 and 2

    i have a form with the checkboxes a form just with that like a preferences/options menu wich is called form3, and the form1 wich is the main form.

    the checkbox states takes effect on form1 ...

     

    so i need to check how they are (checked or not) on the form1 load event...

    then the form3 is the preferences form where are the checboxes so there also need in load event ro read the state of the checkboxes before form opens so need in load event also

    also in form3 have  a button , a single button, named save and exit so on click event need what user checks while form is opened and save the state and exit the form3

    i change , instead of use checkbox i use now checkbox list the way to check if them return true or false, individually is:

    checkedListBox1.GetItemChecked(0) :- for the frist checkbox because index is zero based

    checkedListBox1.GetItemChecked(1) : - for second checkbox

    checkedListBox1.GetItemChecked(2) :- for 3rd checkbox

    so please in you code i just see form1 code so i explain a litle better please adapt your code to this situation specifing wich form you are talking about and also specific the events created....

     

    thanks!

    Saturday, November 12, 2011 1:39 AM
  • > ... a preferences/options menu wich is called form3, and the form1 wich is the main form. [...]
    the checkbox states takes effect on form1 [...]
    form3 have a button , a single button, named save and exit

      
    if i understood correctly, you have to get the second form (some kind of settings editor with checkbox's).
    second form contains save'n'exit button. after button click the checkboxes states should be reflected on the main form.
    so below is an example. hope that is what you wanted.
      

    using System;
    using System.Data;
    using System.IO;
    using System.Windows.Forms;
    
    namespace WindowsFormsApplication0
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                var file = "settings.xml";
                var ds = LoadData(file);
    
                var lbl = new Label
                {
                    Parent = this,
                    Dock = DockStyle.Top,
                    Height = 100,
                    Text = GetText(ds)
                };
    
                this.Menu = new MainMenu();
                this.Menu.MenuItems.Add("Settings", (s, e) =>
                {
                    ds.AcceptChanges();
                    var frm = new Form2(this.BindingContext, ds);
                    frm.Owner = this;
                    var res = frm.ShowDialog();
                    if(res != System.Windows.Forms.DialogResult.OK)
                        ds.RejectChanges();
    
                    lbl.Text = GetText(ds);
                });
    
                this.Closing += (s, e) =>
                {
                    ds.AcceptChanges();
                    ds.WriteXml(file, XmlWriteMode.WriteSchema);
                };
            }
    
            string GetText(object ds)
            {
                return String.Concat(
                    "SkypeMute=", GetState(ds, "data.SkypeMute"),
                    "\nBaixarVolSkype=", GetState(ds, "data.BaixarVolSkype"),
                    "\nMinTarefas=", GetState(ds, "data.MinTarefas")
                    );
            }
    
            bool GetState(object ds, string dm)
            {
                return Convert.ToBoolean(this.BindingContext[ds, dm].Current);
            }
    
            DataSet LoadData(string file)
            {
                var ds = new DataSet();
                if (File.Exists(file))
                    ds.ReadXml(file);
                else
                {
                    var dt = new DataTable("data");
                    dt.Columns.Add("MinTarefas", typeof(bool)).DefaultValue = true;
                    dt.Columns.Add("BaixarVolSkype", typeof(bool)).DefaultValue = true;
                    dt.Columns.Add("SkypeMute", typeof(bool)).DefaultValue = true;
                    ds.Tables.Add(dt);
                    dt.Rows.Add(true, true, true);
                }
                ds.AcceptChanges();
                return ds;
            }
        }
    
        class Form2 : Form
        {
            public Form2(BindingContext bc, object ds)
            {
                this.BindingContext = bc;
    
                new CheckBox { Parent = this, Dock = DockStyle.Top, Text = "MinTarefas" }
                    .DataBindings.Add("Checked", ds, "data.MinTarefas");
    
                var cb2 = new CheckBox { Parent = this, Dock = DockStyle.Top, Text = "BaixarVolSkype" };
                cb2.DataBindings.Add("Checked", ds, "data.BaixarVolSkype");
    
                var cb3 = new CheckBox { Parent = this, Dock = DockStyle.Top, Text = "SkypeMute" };
                cb3.DataBindings.Add("Checked", ds, "data.SkypeMute");
    
                cb2.CheckedChanged += (s, e) =>
                {
                    if (cb2.CheckState == CheckState.Checked)
                        cb3.CheckState = CheckState.Unchecked;
                };
    
                cb3.CheckedChanged += (s, e) =>
                {
                    if (cb3.CheckState == CheckState.Checked)
                        cb2.CheckState = CheckState.Unchecked;
                };
    
                this.Closing += (s, e) =>
                {
                    foreach (Control c in this.Controls)
                        foreach (Binding b in c.DataBindings)
                            b.WriteValue();
                };
    
                new Button 
                {
                    Text = "Save'n'Exit",
                    Parent = this,
                    Location = new System.Drawing.Point(5, 100),
                    DialogResult = System.Windows.Forms.DialogResult.OK
                };
            }
        }
    }
    
    

    • Proposed as answer by Malobukv Saturday, November 12, 2011 11:56 PM
    Saturday, November 12, 2011 11:56 PM
  • ok now code seems ok , but why dont use use events....

     

    i already have the checkboxes implemented so i just need to get their state and save it to the xml and i use a checkbox list so the way to check if they are selected is:

    checkedListBox1.GetItemChecked(0) :- for the frist checkbox because index is zero based

    checkedListBox1.GetItemChecked(1) : - for second checkbox

    checkedListBox1.GetItemChecked(2) :- for 3rd checkbox


    the code is sample the frist checkbox is independent from others it can be cehcked or not the 2 or 3 can only be selected one of them not both!

     

    private void checkedListBox1_ItemCheck(object sender, ItemCheckEventArgs e)
            {
                
                    CheckedListBox.CheckedIndexCollection checkedIndices = checkedListBox1.CheckedIndices;
                    if (checkedIndices.Contains(0) && checkedIndices.Count == 2 && (int)e.NewValue == 1)
                    {
                        checkedListBox1.SetItemChecked((e.Index == 1 ? 2 : 1), false);
                    }
                    if (!checkedIndices.Contains(0) && checkedIndices.Count > 0 && (int)e.NewValue == 1)
                    {
                        checkedListBox1.SetItemChecked((e.Index == 1 ? 2 : 1), false);
                    }
    }
    


    soi think here you are creating them again and is not needed since i have this but add it to your code also please

    and remove this because i think is not need use my logic :

           new CheckBox { Parent = this, Dock = DockStyle.Top, Text = "MinTarefas" }
                    .DataBindings.Add("Checked", ds, "data.MinTarefas");

                var cb2 = new CheckBox { Parent = this, Dock = DockStyle.Top, Text = "BaixarVolSkype" };
                cb2.DataBindings.Add("Checked", ds, "data.BaixarVolSkype");

                var cb3 = new CheckBox { Parent = this, Dock = DockStyle.Top, Text = "SkypeMute" };
                cb3.DataBindings.Add("Checked", ds, "data.SkypeMute");

    also already have the names of each of them in from by using the colletion in design mode  so is this needded??

    DockStyle.Top, Text = "BaixarVolSkype"? is just the name of the checkbox to show to the user take it out i already have or s the name to sae on xml file

    as i said before i use checkbox list and i provied already in this post how to check their state

    please edit your code and post a message like code edited.... then i will check here

     

    EDIT: i need 4 checkboxes so need to save all state from then the 4th calls StarSkypeMinimized, but as i said i already have the code for them wich is here on checkedListBox1_ItemCheck above [actually it just work for 3 but i wil change it soon]

     

    the way to check the 4th checkbox state is checkedListBox1.GetItemChecked(3)
    so you dont need to create them just need to save their state with the code i provide, obvious you need to enter it somewhere else to save to the xml file but i repeat you dont need to create them visually nor care about their selecting mode logic wich also i provide here to integrate your code with mine and just save their state to xml

    checkbox1= true if i was checked and saved buy the user and the same for others
    if should save when user click on saven exit button so the save code must be on that button click event

     




    • Edited by Hugo Luiten Sunday, November 13, 2011 9:07 PM
    Sunday, November 13, 2011 1:11 AM
  • also need a bool var but not on checkbox so just want to know how to read it from xml and change their status. so call it FristTime as bool then i set their state on some part so this is so to use with checkbox
    Monday, November 14, 2011 1:38 PM
  • can reply?


    • Edited by Hugo Luiten Wednesday, November 16, 2011 10:13 AM
    Wednesday, November 16, 2011 10:13 AM