如何将数据gridview导出到xml

问题描述 投票:0回答:1

[我正在尝试使用XDocument将数据gridview保存到XML文件,但问题是当我单击导出按钮时,数据gridview变得清晰并且导出的XML文件为空

此按钮从多个文本框中填充datagridview:

 private void add_Click(object sender, EventArgs e)
 {
     int n = dataGridView1.Rows.Add();

     dataGridView1.Rows[n].Cells[0].Value = txtOne.Text;
     dataGridView1.Rows[n].Cells[1].Value = txtTwo.Text;
     dataGridView1.Rows[n].Cells[2].Value = txtThree.Text; 
 }

此按钮导出为XML:

private void Export_Click(object sender, EventArgs e)
{

const string FILENAME = @"c:\temp\test.xml";
XDocument doc = new XDocument(
new XDeclaration("1.0", "ISO-8859-1", null),
new XElement("root",    
    dt.AsEnumerable().Select(row => new XElement("child", new object[]{
            new XElement("one",row[0]),
            new XElement("two",row[1]),
            new XElement("three",row[2]),
            }));


dataGridView1.DataSource = dt;
doc.Save(FILENAME);
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.InitialDirectory = Convert.ToString(Environment.SpecialFolder.MyDocuments);
saveFileDialog1.Filter = "File Name |*.xml";
saveFileDialog1.FilterIndex = 1;
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
    doc.Save(saveFileDialog1.FileName);
}
c# parsing xml-parsing
1个回答
0
投票

如果要从DataGridView读取所有数据并导出到XDocument,则必须使用两个周期读取所有行和所有单元格。

private void ExportButton_Click(object sender, EventArgs e)
{
    var columnHeaders = (from DataGridViewColumn column in dataGridView1.Columns select column.HeaderText).ToArray();

    var xDoc = new XDocument(
        new XDeclaration("1.0", "ISO-8859-1", null),
        new XElement("root"));

    foreach (DataGridViewRow row in dataGridView1.Rows)
    {
        if (row.IsNewRow)
            continue;

        var xRow = new XElement("row");

        foreach (DataGridViewCell cell in row.Cells)
        {
            xRow.Add(new XElement(columnHeaders[cell.ColumnIndex], cell.Value));
        }

        xDoc.Element("root")?.Add(xRow);
    }

    xDoc.Save(@"d:\tmp\test.xml");
}

如果需要,可以添加saveFileDialog并从对话框中设置文件名

© www.soinside.com 2019 - 2024. All rights reserved.