How to add datagridview rows to an xml file?

前端 未结 2 1885
死守一世寂寞
死守一世寂寞 2021-01-25 11:02

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 D

相关标签:
2条回答
  • 2021-01-25 11:21

    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);
    
    0 讨论(0)
  • 2021-01-25 11:35

    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...

    0 讨论(0)
提交回复
热议问题