I have a DataGridView which displays a list of rail cars and has several buttons for manipulating the list (Add, Edit, Delete, Save). The contents of the DGV come from an XML file and are saved back to the same file when the Save button is clicked. All functions of this form work perfectly with the exception of the Delete button. When I delete a rail car from the list and click Save, it takes the "deleted" row and re-appends it to the XML file in a very weird way (picture below).
Here is the code for the form (I'm only including the Save & Delete buttons and XML handling for ease of reading):
public partial class SimulatedTrainEditor : Form { //fileName and XML variables for serialization/deserialization const string fileName = "SimulatedTrain1.xml"; XmlSerializer xml = new XmlSerializer(typeof(BindingList<SimulatedTrain>)); //Create BindingList object to hold XML data public BindingList<SimulatedTrain> NewSimulatedTrain = new BindingList<SimulatedTrain>(); public bool WereChangesMade; public SimulatedTrainEditor() { InitializeComponent(); LoadXML(); this.dataGridViewSimulatedTrainEditor.DataSource = NewSimulatedTrain; this.dataGridViewSimulatedTrainEditor.SelectionMode = DataGridViewSelectionMode.FullRowSelect; this.dataGridViewSimulatedTrainEditor.AllowUserToAddRows = false; this.WereChangesMade = false; this.buttonSaveXML.Enabled = false; } public void LoadXML() { try { using (var fs = new FileStream(fileName, FileMode.Open)) { NewSimulatedTrain = (BindingList<SimulatedTrain>)xml.Deserialize(fs); } } catch (Exception ex) { Console.WriteLine(ex.Message, ex); } } private void buttonRemoveRailCar_Click(object sender, EventArgs e) { var currentRow = this.dataGridViewSimulatedTrainEditor.CurrentRow; if (currentRow != null) { this.NewSimulatedTrain.RemoveAt(currentRow.Index); this.WereChangesMade = true; this.buttonSaveXML.Enabled = true; } } private void buttonSaveXML_Click(object sender, EventArgs e) { //are there any changes? if (WereChangesMade) { //save the file if changes using (var fs = new FileStream(fileName, FileMode.OpenOrCreate)) { xml.Serialize(fs, this.NewSimulatedTrain); } //Disable the SaveXML button when it's clicked to look for new edits after each save this.buttonSaveXML.Enabled = false; } } } And here are screenshots of before and after I delete a row (this is just the bottom portion of the XML):
After (the red bit should be the end of the XML file): 
You can see it tries to add another closing ArrayOfSimulatedTrain tag to the end after it throws in the row data that should have been deleted. I am still getting use to working with XML files, but in the few instances I've done this type of work before, I've never run into this particular issue.

No comments:
Post a Comment