How to add datagridview rows to an xml file?

半世苍凉 提交于 2019-12-31 04:11:09

问题


I am a beginner in c#, I created one dataGridView1 in a Form to which I added some rows and columns (without using DataSet and Datatable). Now I need to send the data of dataGridView1 to an xml file. The xml file should update whenever I click on that button. I need to do this without using Datatable (or tables). I tried the below code (not working)

OnButtonClick

        XmlTextWriter newXml = new XmlTextWriter("d:/newXML.xml", Encoding.UTF8);
        DataSet ds = new DataSet(dataGridView1.Rows.ToString()); /* May be I am missing something here */
        ds.WriteXml(newXml);

xml file is created successfully but showing <System.Windows.Forms.DataGridViewRowCollection /> in it.

If I add BindingSource bs = (BindingSource)dataGridView1.DataSource; before DataSet, it is showing error "Object reference not set to an instance of an object."

Note: If the xml file is not their then it should create one.

Thanks in advance.


回答1:


You can instantiate a DataTable and populate it from your dataGridView1 control:

        DataTable table = new DataTable("Customers");
        // copy the correct structure from datagridview to the table
        foreach (DataGridViewColumn column in dataGridView1.Columns)
        {
            table.Columns.Add(column.Name, typeof(string));
        }

        // populate the datatable from datagridview
        for (int rowIndex = 0; rowIndex < dataGridView1.Rows.Count; rowIndex++)
        {
            table.Rows.Add();
            for (int columnIndex = 0; columnIndex < dataGridView1.Columns.Count; columnIndex++)
            {
                table.Rows[rowIndex][columnIndex] = dataGridView1[rowIndex, columnIndex].Value;
            }
        }

then continue with the rest of your code:

    DataSet ds = new DataSet();
    ds.Tables.Add(table);
    ds.WriteXml("d:/newXML.xml", System.Data.XmlWriteMode.IgnoreSchema);



回答2:


Welcome to the C# world !

A good start to solve your problem should be to use Serialization, it's really handy when you need to save Objects into an XML file.

I don't know how you store the Objects that fills the DataGrid but if you can, you should make them serializable, add some methods like Load(), Save(), etc.

Read this for more informations : MSDN - Serialization

You'll find plenty informations on how to do this, a little bit harsh to implement when you start but saves you a damn lot of time further on the road !

Hope it will help.

EDIT 1 :

Just saw your edits, it seems like you're not using Objects, just plain inserts. In that case, my solution won't help but think about it for more complex situations...



来源:https://stackoverflow.com/questions/12599396/how-to-add-datagridview-rows-to-an-xml-file

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