How to add datagridview rows to an xml file?

前端 未结 2 1908
死守一世寂寞
死守一世寂寞 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);
    

提交回复
热议问题