如何使用序列化将datagridview转换为xml文件?

时间:2013-01-09 15:00:56

标签: c# xml datagridview

如何使用序列化将datagridview转换为xml文件?

以下代码无效,因为dt始终为null

 DataTable dt = new DataTable();
 dt = dataGridView1.DataSource as DataTable;
 DataSet ds = new DataSet();
 ds.Tables.Add(dt);
 ds.WriteXml(@"e:\results.xml", System.Data.XmlWriteMode.IgnoreSchema);

提前谢谢。

1 个答案:

答案 0 :(得分:1)

        BindingSource bs = new BindingSource();
        DataTable dt = new DataTable();
        DataSet ds = new DataSet();

        dt.Columns.Add("1", typeof(int));
        dt.Columns.Add("2");
        dt.Columns.Add("3");
        dt.Columns.Add("4");
        dt.Columns.Add("5");

        string[] row = {null,"dsadxaxsa","xasxsa","","dsad"};
        string[] row1 = { "1", "ddd", "gg", "hh", "ff" };
        string[] row2 = { "2", "h", "hhhh", "sas", "dsad" };
        string[] row3 = { "3", "h", "hhhh", "sas", "dsad" };
        string[] row4 = { null, "h", "hhhh", "sas", "dsad" };
        dt.Rows.Add(row);
        dt.Rows.Add(row1);
        dt.Rows.Add(row2);
        dt.Rows.Add(row3);
        dt.Rows.Add(row4);

        bs.DataSource = dt;
        dataGridView1.DataSource = bs;

        ds.Tables.Add(dt);
        ds.WriteXml("e:\\results.xml", System.Data.XmlWriteMode.IgnoreSchema);