我目前正在从 SQL Server 获取数据并存储在 DataTable 中。我正在对该 DataTable 应用 GroupBy 操作,以便在 DataGrid 中以各种形式显示该表。制作子数据表后,我通过放置在数据视图中对数据表进行排序。对 DataView 进行排序后,我将其绑定到 DataGridView。但问题是 GroupBy 生成的行没有正确排序
我可以得到解决方案吗?
这是 DataView GroupBy 代码。
DataView view = new DataView(dtfullreport); // Datatable to dataview.
var drdatedisp = from row in dtfullreport.AsEnumerable()
group row by row.Field<string>("Order_Date") into g
select new
{
Order_Date = g.Key,
totalQnty = g.Sum(a => a.Field<int>("Item_Quantity")),
totalTax = g.Sum(a => float.Parse(a.Field<decimal>("TAXAMT").ToString())),
totalAmt = g.Sum(a => float.Parse(a.Field<decimal>("VALAMT").ToString()))
};
DataTable dtdatedisp = new DataTable();
dtdatedisp.Columns.Add("Order_Date");
dtdatedisp.Columns.Add("Item_Quantity");
dtdatedisp.Columns.Add("TAXAMT");
dtdatedisp.Columns.Add("VALAMT");
dtdatedisp.Rows.Clear();
foreach (var g in drdatedisp)
{
DataRow newRow1 = dtdatedisp.NewRow();
newRow1[0] = g.Order_Date;
newRow1[1] = g.totalQnty;
newRow1[2] = String.Format("{0:0.00}", g.totalTax);
newRow1[3] = String.Format("{0:0.00}", g.totalAmt);
dtdatedisp.Rows.Add(newRow1);
}
在对 DataView 进行分组并放入 DataTable 之后,我正在对 DataTable 进行排序
这是排序代码。这将写在 GridView 排序事件中。
string sortingDirection = string.Empty;
if (dir == SortDirection.Ascending)
{
dir = SortDirection.Descending;
sortingDirection = "Desc";
}
else
{
dir = SortDirection.Ascending;
sortingDirection = "Asc";
}
DataView sortedView = new DataView((DataTable)ViewState["dtdatedisp"]);
sortedView.Sort = e.SortExpression + " " + sortingDirection;
gv_reports_date.DataSource = sortedView; // Gridview datasource and binding
gv_reports_date.DataBind();
我正在根据 Order_Date 列进行排序,但是在按降序对 DataView 进行排序后,输出是,
Datatable before Grouping
Default View before sorting. (Sorted according to date in database).
After sorting in Descending order of Quantity Sold.
After sorting in Ascending order of Quantity Sold.
The Rows which are Grouped are not being displayed in correct Sort Order