【问题标题】:How to export data gridview to xml如何将数据gridview导出到xml
【发布时间】:2020-05-27 10:25:14
【问题描述】:

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

这个按钮从多个文本框填充数据网格视图:

 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);
}

【问题讨论】:

  • 请提供最小的、可重现的示例。 stackoverflow.com/help/minimal-reproducible-example
  • 由于您的数据源是一个数据表,您可以在一条指令 dt.WriteXml(filename) 中将数据表写入 xml。不要用新数据填充 DGV,而是将新数据添加到数据表中。

标签: c# parsing xml-parsing


【解决方案1】:

如果您想从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 并从对话框中设置文件名

【讨论】:

  • 是否可以制作像这样的xml架构<root> <row> <one>125</one> <two>125</two> <child> <three>987</three> </child> </row> </root>
  • 您可以将if 添加到两个循环和列的列索引或标题名称中,然后执行您需要的操作(使用子元素创建新元素或跳过此列或...)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-06-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-21
  • 1970-01-01
  • 2016-05-28
相关资源
最近更新 更多