Hi iammann,
check this example now please take its reference and correct your code.
HTML
<asp:Label ID="lblTable" runat="server" />
Namespaces
C#
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
DataTable dtProducts = new DataTable();
dtProducts.Columns.Add("OrderID", typeof(int));
dtProducts.Columns.Add("ProductName", typeof(string));
dtProducts.Columns.Add("Price", typeof(double));
dtProducts.Rows.Add(1001, "Apple", 100.00);
dtProducts.Rows.Add(1001, "Orange", 50.00);
dtProducts.Rows.Add(1002, "Banana", 40.00);
dtProducts.Rows.Add(1003, "Grapes", 110.00);
dtProducts.Rows.Add(1003, "Litche", 210.00);
dtProducts.Rows.Add(1004, "Mango", 120.00);
double total = 0;
string table = "<table><tr><th>OrderID</th><th>ProductName</th><th>Price</th></tr>";
var result = from dr in dtProducts.AsEnumerable()
group dr by dr["OrderID"] into cg
select new
{
row = cg.CopyToDataTable(),
sum = cg.Sum(dr => Convert.ToDouble(dr["Price"]))
};
foreach (var item in result)
{
DataTable dt = item.row;
for (int i = 0; i < dt.Rows.Count; i++)
{
table += "<tr><td>" + dt.Rows[i]["OrderID"] + "</td><td>" + dt.Rows[i]["ProductName"] + "</td><td>" + dt.Rows[i]["Price"] + "</td><tr>";
}
table += "<tr><td></td><td><b>Sub Total</b></td><td><b>" + item.sum + "</b></td><tr>";
total += item.sum;
}
table += "<tr><td></td><td><b>Total</b></td><td><b>" + total + "</b></td><tr>";
table += "</table>";
lblTable.Text = table;
}
}
Screenshot