Windows Form Save to XML

2019-02-20 20:51发布

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条回答
混吃等死
2楼-- · 2019-02-20 21:48

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);
    }
}
查看更多
登录 后发表回答