在C#中将XML文件内容添加到dataGridView吗? [英] Add XML File Contents to a dataGridView in C#?

查看:64
本文介绍了在C#中将XML文件内容添加到dataGridView吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,这是我的问题。我正在创建我的第一个C#应用程序之一。这将是一种库存管理器。有一个dataGridView,其中使用行和列显示数据。您可以在dataGridView中添加,删除和更新任何行。您还可以将dataGridView中的内容另存为XML文件。我的问题是我不知道如何将XML文件加载回dataGridView以便将来编辑网格?

So, here's my problem. I am creating one of my first C# applications. It is going to be a type of inventory manager. There's a dataGridView where the data is displayed using Rows and Columns. You can Add, Delete, and Update any row within the dataGridView. You can also save the contents that are in the dataGridView as an XML file. My problem is that I don't know how to load that XML file back into the dataGridView for future editing of the grid?

dataGridView行中的数据是

The data in the rows of the dataGridView are added using a DataTable.

以下是我的意思的示例:

Here's an example of what I mean:

dataTable.Rows.Add(txtID.Text, txtName.Text);
dataGridView1.DataSource = dataTable;

我只需要从XML获取行的数据,因为添加了列名

I only need to get the data for the rows from the XML because the names of the columns are added when the form loads.

以下是XML格式:

<NewDataSet>
  <Table1>
    <ID>AN ID</ID>
    <Name>A NAME</Name>
  </Table1>
  <Table1>
    <ID>ANOTHER ID</ID>
    <Name>ANOTHER NAME</Name>
  </Table1>
  <Table1>
     <ID>YET ANOTHER ID AND SO ON</ID>
     <Name>YET ANOTHER NAME AND SO ON</Name>
  </Table1>
</NewDataSet>

我不知道这是否重要,但是XML文件的名称是Contents.xml,它位于应用程序的启动位置。

And I don't know if this matters, but the XML file's name is Contents.xml and it is located in the application's startup location.

我不确定我是否有意义?

I'm not sure if I'm making any sense?

谢谢! :)

推荐答案

您可以使用以下方式:

    private void button1_Click(object sender, EventArgs e)
    {
        DataTable dt = new DataTable();

        string xml = @"<NewDataSet>
                      <Table1>
                        <ID>AN ID</ID>
                        <Name>A NAME</Name>
                      </Table1>
                      <Table1>
                        <ID>ANOTHER ID</ID>
                        <Name>ANOTHER NAME</Name>
                      </Table1>
                      <Table1>
                         <ID>YET ANOTHER ID AND SO ON</ID>
                         <Name>YET ANOTHER NAME AND SO ON</Name>
                        <Bonus>Bonus Column</Bonus>
                      </Table1>
                    </NewDataSet>";

        using (DataSet ds = new DataSet())
        {
            using (MemoryStream mStrm = new MemoryStream(Encoding.UTF8.GetBytes(xml)))
            {
                ds.ReadXml(mStrm);
                dataGridView1.DataSource = ds.Tables[0];
            }
        }
    }

这篇关于在C#中将XML文件内容添加到dataGridView吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆