Reputation: 133
Hello Friends I need to group the elements of GridView as shown below. I need to sum up the price according to its ID's
Data in GridView
1-------------1-------------100
2-------------1-------------150
3-------------1-------------120
4-------------2-------------120
5-------------2-------------160
6-------------3-------------100
7-------------3-------------200
I want to group this data as shown below and save it in a datatable so that I can pass it to my Database.
1------------370
2------------280
3------------300
How do I do this? Thanks in advance
Upvotes: 0
Views: 723
Reputation: 63065
change your select statement as below
SELECT ID2, SUM(Price) FROM TableName GROUP BY ID2
you can do as below if you need to read from gridview
List<Record> records = new Record<Record>();
foreach (GridViewRow row in grid.Rows)
{
// below code need to be change with your grid controls and id names, and add validations for handle null values etc..
string id2 = ((Label)row.FindControl("ID2Label")).Text;
string Price = ((TextBox)row.FindControl("PricetextBox")).Text;
records.Add(new Record(){ ID2 = int.Parse(id2), Price = int.Parse(Price)});
}
var results = records.GroupBy(r=>r.ID2)
.Select(g=> new Record(){ ID2 = g.Key, Price = g.Sum(x=>x.Price)})
.ToList();
you may need helper class like below
public class Record
{
public int ID2 { get; set;}
public int Price {get; set;}
}
Upvotes: 2