【问题标题】:How to fill a DataTable with XElement/XAttribute?如何用 XElement/XAttribute 填充 DataTable?
【发布时间】:2018-04-09 08:02:06
【问题描述】:

我是 C# 新手,以前从未使用过 DataTable。

我想要一个具有特定名称的 DataGridView。

        DataTable table = new DataTable();
        List<string> bla = new List<string>();

        XDocument config = XDocument.Load(configFile);

        Dictionary<string, string> dict = config.Descendants("Columns").FirstOrDefault().Elements()
            .GroupBy(x => (string)x.Attribute("XPath"), y => (string)y.Attribute("Name"))
            .ToDictionary(x => x.Key, y => y.FirstOrDefault());

        //I dont know if I need this:
        foreach (string key in dict.Keys)
        {
            table.Columns.Add(key, typeof(string));
        }


        foreach (XElement position in positions.Where(e => e.HasAttributes))
        {
            foreach (XAttribute attribute in position.Attributes().Where(a => dict.ContainsKey($"@{a.Name.LocalName}")))
            {
                string name = attribute.Name.LocalName;
                string value = (string)attribute;
                string xName = dict["@" + name];

                bla.Add(xName);
            }

列的名称应来自 xName。

我该怎么做?

我试过了:

            foreach (var item in bla)
            {
                DataRow row = table.NewRow();
                row.SetField<string>(item); //this didn't work.

                //foreach (string key in dict.Keys)
                //{
                //    row.SetField<string>(key, item[key]);
                //}
            }

只想将 xName 中的名称作为我的输出标题。

xName 示例:职位、状态、订单、编号... 作为我的标题。 而在这之下的价值观。

【问题讨论】:

    标签: c# winforms datatable


    【解决方案1】:

    如果我对您的理解正确,您的列名列表就可以了,但不知道如何使用正确的列名创建数据表。

    以下是如何将列和行添加到具有特定列标题名称的数据表的示例。

    正如 cmets 中所讨论的,我已经演示了一个将您需要的数据放入允许您填充表格的结构中的过程。

          //Class to hold data
      public class MyRecordContent
      {
            public MyRecordContent()
            {
                //initialise list
                RecordsColumns = new List<string>();
            }
    
            //Holds a list of strings for each column of the record.
            //It starts at position 0 to however many columns you have
            public List<string> RecordsColumns { get; set; }
      }
    
                //This creates an empty table with the columns
                var myTable = new DataTable("Table1");
                foreach (var item in bla)
                {
                    if (!myTable.Columns.Contains(item))
                    {
                        myTable.Columns.Add(new DataColumn(item, typeof(string)));
                    }
                }
    
    
    
             //Here you build up a list of all records and their field content from your xml.
            foreach (var xmlNode in yourXMLRecordCollection)
            {
                var thisRecord = new MyRecordContent();
    
                foreach (var xmlCol in xmlNode.Elements)//Each column value
                {
                    thisRecord.RecordsColumns.Add(xmlCol.GetValue());
                }
    
                myListOfRecords.Add(thisRecord);
            }
    
            foreach (MyRecordContent record in myListOfRecords)
            {
                var row = myTable.NewRow();
    
                //Here we set each row column values in the datatable.
                //Map each rows column value to be the value in the list at same position.
                for (var colPosition = 0; colPosition <= myTable.Columns.Count - 1;) //Number of columns added.
                {
                    row[colPosition] = record.RecordsColumns[colPosition];
                }
    
                myTable.Rows.Add(row);
            }
    

    在上面,遍历列名列表并将每一列添加到表中。如果需要,您可能希望将 switch 语句添加到循环中以根据名称更改列的数据类型。然后从该表中创建新行并相应地设置每个字段值。 最后,将新行添加到数据表中。

    希望对您有所帮助。

    然后

    【讨论】:

    • 啊,谢谢!是的,我不知道如何使用正确的列名创建数据表。但是对于"MyColumnName",我应该采用item 还是不呢?否则它会说“列‘.....’不属于表”?
    • @Lizzy - 是的。如果 item 是您的字符串列名,则将“MyColumnName”替换为 item。
    • 好的。 "FieldValue" 是怎么回事?这说明了什么?另一个问题:我有更多具有相同名称但值不同的 xName ......所以它说“列已经存在”。 ?
    • @Lizzy - "FieldValue" 向您展示了如何为当前行设置列的值。因此,将该文本替换为该字段中应有的内容。理想情况下,您需要创建一个唯一的列名列表以防止重复。但是您可以检查一下,我已将其添加到我的答案中。
    • 谢谢,这行得通! :) 所以在row[heading] = "FieldValue"; 中,我必须将另一个foreach 中的value 放在此处。但我无法访问该值。嗯..我该怎么做..?
    猜你喜欢
    • 2011-06-27
    • 1970-01-01
    • 1970-01-01
    • 2012-08-13
    • 1970-01-01
    • 2015-02-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多