将DataGridView保存到XML文件

时间:2015-12-21 16:27:14

标签: c# asp.net xml datagridview

好吧,所以我在这个主题上看到了几个不同的帖子,每个帖子都有一个奇怪而独立的答案,但没有一个适应我的情况:

我有一个DataGridView,它通过用户界面和按钮点击(没有其他数据源)一次填充一行。一旦DGV满足用户的满意度,他们就可以点击一个按钮,将当前的DGV数据保存到XML文件中。

我尝试通过DataSet或DataTable来做这件事,但文件创建对我来说仍然是一个新概念,我不认为我看到了整个画面来解决我做错的事情

第一个代码块是将用户输入数据从用户窗口带到DGV:

 //Function for the Add Car button to open the Add New Car window
    private void buttonAddCar_Click(object sender, EventArgs e)
    {
        AddNewCar displayNewCarWindow = new AddNewCar();

        displayNewCarWindow.ShowDialog();

        dataGridViewMainCarDisplay.Rows.Add(displayNewCarWindow.NewTrainName
                                           , displayNewCarWindow.NewTrainWidth
                                           , displayNewCarWindow.NewTrainHeight
                                           , displayNewCarWindow.NewTrainLength
                                           , displayNewCarWindow.NewTrainDeadWeight
                                           , displayNewCarWindow.NewTrainLoadCapacity);
    }

第二个代码块是我在处理现已完成的DGV数据并将其打包发送到XML时出现问题的地方:

/*  Function for the Load XML button to send all data populated
             in the DataGridView to an XML file                     */
    private void buttonLoadXML_Click(object sender, EventArgs e)
    {
        //Create a file path and name to store the serialized data
        string fileName = @"C:\Users\a.watts\Documents\Visual Studio 2015\Projects\SerializationTrainTypeDemo\XMLRecording\data.xml";

        //Create a dataTable to bind the DataGridView to for serialization
        DataTable dataTable = new DataTable();

        //Bind the DataGridView to the dataTable
        for (int i = 0; i < dataGridViewMainCarDisplay.Rows.Count; i++)
        {
            //Some stuff here to save each DataGridView row one at a time
        }

        //Write the DataGridView data in the dataTable to an XML
        dataTable.WriteXml(fileName);
    }

1 个答案:

答案 0 :(得分:1)

好的,这是您要找的部分。

将数据表绑定到dataGridView。 https://msdn.microsoft.com/en-us/library/fbk67b6z%28v=vs.110%29.aspx

这是一个将列添加到DataTable并绑定到数据网格视图的简单示例。

        dataGridView1.AutoGenerateColumns = true;
        dataGridView1.AllowUserToAddRows = true;

        DataTable gridTable = new DataTable();
        gridTable.Columns.Add("EmployeeName", typeof(string));
        gridTable.Columns.Add("StartDate", typeof(DateTime));
        gridTable.Columns.Add("Salary", typeof(double));
        gridTable.Columns.Add("Location", typeof(string));

        dataGridView1.DataSource = gridTable;

当数据添加到网格时,它将被添加到数据表中。然后,您需要将数据表序列化为XML文件。稍后,您可能希望将XML文件反序列化为数据表。在下面的示例中,您将Models.ProjectModel更改为您正在使用的对象 - DataTable。

public class ProjectDataAccess : IProjectDataAccess
{
    public Models.ProjectModel Get(string filePath)
    {
        Models.ProjectModel project = new Models.ProjectModel();

        // Construct an instance of the XmlSerializer with the type
        // of object that is being deserialized.
        XmlSerializer xmlSerializer = new XmlSerializer(typeof(Models.ProjectModel));

        // To read the file, create a FileStream.
        FileStream fileStream = new FileStream(filePath, FileMode.Open);

        // Call the Deserialize method and cast to the object type.
        project = (Models.ProjectModel)xmlSerializer.Deserialize(fileStream);

        fileStream.Close();
        return project;
    }

    public void Save(Models.ProjectModel project, string filePath)
    {
        System.Xml.Serialization.XmlSerializer xmlSerializer = new System.Xml.Serialization.XmlSerializer(project.GetType());
        StreamWriter streamWriter = new StreamWriter(filePath);
        xmlSerializer.Serialize(streamWriter, project);
        streamWriter.Close();
    }
}