c# - How do i save and load with streamwriter and streamreader -
i have 3 forms, main form month calendar , panel shows appointment, , 2 others,form2 , form3 opening button main form. want have save button in form2 , form3 , when pressed, save information enter in textboxes , selected combobox , when application close , open again, information should load , show in panel.(with streamwriter , streamreader)
i tried xml method can't find out hope method me!
here xml solution
using system; using system.collections.generic; using system.componentmodel; using system.data; using system.drawing; using system.linq; using system.text; using system.windows.forms; using system.xml; using system.xml.serialization; using system.io; namespace windowsformsapplication6 { public partial class form1 : form { const string filename = @"c:\temp\test.txt"; list<textbox> boxes = null; list<combobox> cboxes = null; public form1() { initializecomponent(); this.formclosing += new formclosingeventhandler(form1_formclosing); boxes = new list<textbox>() { textbox1, textbox2, textbox3 }; cboxes = new list<combobox>() { combobox1, combobox2, combobox3 }; xmlserializer xs = new xmlserializer(typeof(root)); xmltextreader reader = new xmltextreader(filename); root newroot = (root)xs.deserialize(reader); foreach (textbox tbox in boxes) { string name = tbox.name; box box = newroot.boxes.where(x => x.name == name).firstordefault(); tbox.text = box.rows[0]; } foreach (combobox cbox in cboxes) { string name = cbox.name; box box = newroot.boxes.where(x => x.name == name).firstordefault(); foreach (string row in box.rows) { cbox.items.add(row); } } } private void form1_formclosing(object sender, formclosingeventargs e) { root root = new root(); root.boxes = new list<box>(); foreach(textbox tbox in boxes) { box newbox = new box() { name = tbox.name, type = "text", rows = new list<string>(){tbox.text} }; } foreach (combobox cbox in cboxes) { box newbox = new box() { name = cbox.name, type = "combo", rows = getrows(cbox) }; } xmlserializer serializer = new xmlserializer(typeof(root)); streamwriter writer = new streamwriter(filename); xmlserializernamespaces _ns = new xmlserializernamespaces(); _ns.add("", ""); serializer.serialize(writer, root, _ns); writer.flush(); writer.close(); writer.dispose(); } private list<string> getrows(combobox cbox) { list<string> rows = new list<string>(); foreach (string row in cbox.items) { rows.add(row); } return rows; } } [xmlroot("root")] public class root { [xmlelement("boxes")] public list<box> boxes { get; set; } } [xmlroot("box")] public class box { public string name { get; set; } public string type { get; set; } [xmlelement("rows")] public list<string> rows { get; set; } } }
Comments
Post a Comment