Windows Form Save to XML

后端 未结 1 1076
野性不改
野性不改 2021-01-16 17:05

I have a form with information in it that the user enters, i want to save this to XML... i\'m fairly new to programming but have read XML is the best thing to use. How would

相关标签:
1条回答
  • 2021-01-16 17:57

    The easiest thing would be to create a class that stores those 10 values as properties and use xml serialization to convert it to XML, then store it to the file system.

    Here's a tutorial: http://www.switchonthecode.com/tutorials/csharp-tutorial-xml-serialization

    More Detail:

    This is super basic Object Oriented/Windows Forms stuff.

    Create a Class that stores each of the values:

    public class Values{
        public string YourFirstValue { get; set;}
        public DateTime YourSecondValue { get; set;}
        ...
    }
    

    and of course you'd want names that map to their actual meanings, but these should suffice for now.

    Then, when clicking a button on your form, store the values in that class:

    void Button1_OnClick(object sender, EventArgs args){
        Values v = new Values();
        v.YourFirstValue = this.FirstField.Text;
        v.YourSecondValue = this.YourSecondField.Value
        ...
        SaveValues(v);
    }
    

    Then implement the SaveValues method to serialize the xml using XmlSerializer for the serialization and StreamWriter to store the result to a file.

    public void SaveValues(Values v){
        XmlSerializer serializer = new XmlSerializer(typeof(Values));
        using(TextWriter textWriter = new StreamWriter(@"C:\TheFileYouWantToStore.xml")){
            serializer.Serialize(textWriter, movie);
        }
    }
    
    0 讨论(0)
提交回复
热议问题