【发布时间】:2014-01-25 18:18:08
【问题描述】:
我对 C# 和 WPF 还很陌生,而且我的暴露主要是自己造成的,所以我认为我可能遗漏了一些明显的东西。然而,它似乎如此很明显,它没有在几个小时的搜索中出现。
由于我只是想弄清楚处理,所有数据都是任意的,简单的,有点傻。
我在一个名为 dt1 的 DataTable 中有这些数据:
Name Count Date
Fred 1 12/01/13
Fred 2 12/02/13
Fred 3 12/03/13
Fred 4 12/04/13
Barney 4 12/01/13
Barney 3 12/02/13
Barney 2 12/03/13
Barney 1 12/04/13
Wilma 1 12/01/13
Wilma 2 12/02/13
Wilma 3 12/03/13
Wilma 4 12/04/13
Betty 4 12/01/13
Betty 3 12/02/13
Betty 2 12/03/13
Betty 1 12/04/13
(列分别为string、int和string)
我要做的是创建第二个 DataTable,每个名称都有一行,每个日期的计数显示在单独的列中,因此:
Name 12/01/13 12/02/13 12/03/13 12/04/13
Fred 1 2 3 4
...
这是我用来填充第二个 DataTable 的代码:
DataTable dt2 = new DataTable();
//add columns for the target dates
dt2.Columns.Add("Name", typeof(string));
for (int n = 1; n < 5; n++)
{
dt2.Columns.Add(String.Format("12/0{0}/13", n.ToString()), typeof(int));
}
DataRow pivotRow = dt2.NewRow();
foreach (DataRow row in dt1.Rows) //step through the rows in the source table
{
if (pivotRow[0].ToString() != row[0].ToString()) //if this is a "new" name in the data set
{
if (pivotRow[0].ToString() != "") //and it's not the first row of the data set
dt2.Rows.Add(pivotRow); //add the row we've been working on
pivotRow = dt2.NewRow(); //create a new row for the "next" name
pivotRow[0] = row[0].ToString(); //add the "next" name to the name column
}
//match the string date stored in column 2 of the source DataTable to the column name in the target one, and put the associated int value in that column
pivotRow[row[2].ToString()] = (int)row[1];
}
//once we've finished the whole source DataTable, add the final row to the target DataTable
dt2.Rows.Add(pivotRow);
//at this point, looking at it through the locals window everything *appears* to be peachy in dt2
GridView.ItemsSource = dt2.DefaultView; //and here, it's all the pits.
这是在 DataGrid 中显示的内容:
Name 12/01/13 12/02/13 12/03/13 12/04/13
Fred
Barney
Wilma
Betty
显然 something 正在被保存,因为它保存了行首的名称,但同样明显的是它没有保存其余的数据点。
我的头骨因撞在这堵特殊的墙上而变得糊状,所以我决定向比我更了解(很多)的人寻求帮助。
我们将不胜感激任何见解或建议。
【问题讨论】:
标签: c# wpf datagrid datatable datarow