Windows Form Save to XML

夙愿已清 提交于 2019-12-04 02:21:43

问题


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 i go about it? If it helps im using Sharp Develop as an IDE. Current it has 10 text boxes and 10 datetimepickers.


回答1:


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);
    }
}


来源:https://stackoverflow.com/questions/10334949/windows-form-save-to-xml

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!