我是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的名称作为输出的标题。
例für xName:位置,地位,顺序,号码,.作为我的航向。在这个价值之下。
发布于 2018-04-09 08:20:43
如果我正确地理解了您,您已经得到了列名列表,但不知道如何创建一个具有正确列名的datatable。
下面是如何向具有特定列标题的datatable添加列和行的示例。
正如注释中所讨论的那样,我演示了将需要的数据输入到允许填充表的结构中的过程。
//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);
}在上面,通过列名列表进行itterate,并将每一列添加到表中。您可能需要向循环中添加一个switch语句,以便根据需要根据名称更改列的数据类型。然后从该表中创建新行,并相应地设置每个字段的值。最后,将新行添加到datatable。
希望这能有所帮助。
然后
https://stackoverflow.com/questions/49728126
复制相似问题