简体   繁体   English

将XML文件打开到数据网格视图算法中,数据表不支持从xml进行模式推断

[英]Open XML File into data grid view algorithm, datatable doesn't support schema inference from xml

so I have found the below code for save to take what is in a datagridview and save it to an xml file. 因此,我发现以下用于保存的代码采用datagridview中的内容并将其保存到xml文件中。 I am trying to write the function that does the opposite (open). 我正在尝试编写执行相反功能(打开)的函数。 So far I have the below code and it works until the rows section. 到目前为止,我有下面的代码,它可以工作到行部分。 I can't quite figure out the logic at the bottom to do what I need it to do. 我无法完全弄清楚执行所需的逻辑。 So far all I'm getting are errors about types not matching. 到目前为止,我得到的只是有关类型不匹配的错误。 Any help would be appreciated. 任何帮助,将不胜感激。 Also I'm getting an odd error in the open function about DataTable does not support schema inference from Xml. 另外我在关于DataTable的open函数中遇到一个奇怪的错误,该错误不支持Xml的模式推断。 When I try to readxml? 当我尝试读取XML时?

private void saveToolStripMenuItem_Click(object sender, EventArgs e)
        {
            DataTable dt = new DataTable("itemstable");

            for (int i = 0; i < dataGridView1.ColumnCount; i++)
            {
                dt.Columns.Add(dataGridView1.Columns[i].Name, typeof(System.String));
            }

            DataRow myrow;
            int icols = dataGridView1.Columns.Count;
            foreach (DataGridViewRow drow in this.dataGridView1.Rows)
            {
                myrow = dt.NewRow();
                for (int i = 0; i <= icols - 1; i++)
                {

                    myrow[i] = drow.Cells[i].Value;
                }
                dt.Rows.Add(myrow);
            }

            dt.WriteXml("items.xml");
        }

        private void openToolStripMenuItem_Click(object sender, EventArgs e)
        {
            DataTable dt = new DataTable("itemstable");

            dt.ReadXml("items.xml");

            for (int i = 0; i < dt.Columns.Count; i++)
            {
                dataGridView1.Columns.Add(dt.Columns[i].ColumnName.ToString(), dt.Columns[i].ColumnName.ToString());
            }

            DataRow myrow;
            int icols = dt.Columns.Count;
            foreach (DataRow drow in dt.Rows)
            {
                myrow = dataGrideView1.NewRow();
                for (int i = 0; i <= icols - 1; i++)
                {

                    myrow[i] = drow.Cells[i].Value;
                }
                dt.Rows.Add(myrow);
            }

I was able to open my file using the following code: 我可以使用以下代码打开文件:

private void openToolStripMenuItem_Click(object sender, EventArgs e)
    {
        DataSet ds = new DataSet();
        ds.ReadXml("items.xml");
        dataGridView1.Columns.Clear();
        dataGridView1.DataSource = ds.Tables[0];           
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM