If you have Linkbutton in asp.net ,you did't get Total ,sub Total in Row Data Bound if you using Model Popup.So you need to get subtotal,grand total in Datatable itself.The given below example give you the Group Names{ProjectName} based total,subtotal using Linq.
Output:
Dataset Input:
Dataset OUTPUT:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
//added namespace
using System.Linq;
namespace testDatatablesum
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private DataTable getdata()
{
DataTable dt = new DataTable();
dt.Columns.Add("ProjectName");
dt.Columns.Add("Source");
dt.Columns.Add("SourceAmount");
// Add Rows
DataRow rowA1 = dt.NewRow();
rowA1["ProjectName"] = "A";
rowA1["Source"] = "ABC";
rowA1["SourceAmount"] = "10000";
dt.Rows.Add(rowA1);
DataRow rowA2 = dt.NewRow();
rowA2["ProjectName"] = "A";
rowA2["Source"] = "XYZ";
rowA2["SourceAmount"] = "50200";
dt.Rows.Add(rowA2);
DataRow rowA3 = dt.NewRow();
rowA3["ProjectName"] = "A";
rowA3["Source"] = "DFG";
rowA3["SourceAmount"] = "27000";
dt.Rows.Add(rowA3);
DataRow rowB1 = dt.NewRow();
rowB1["ProjectName"] = "B";
rowB1["Source"] = "LMN";
rowB1["SourceAmount"] = "12990";
dt.Rows.Add(rowB1);
DataRow rowB2 = dt.NewRow();
rowB2["ProjectName"] = "B";
rowB2["Source"] = "PQR";
rowB2["SourceAmount"] = "14000";
dt.Rows.Add(rowB2);
DataRow rowC1 = dt.NewRow();
rowC1["ProjectName"] = "C";
rowC1["Source"] = "KLM";
rowC1["SourceAmount"] = "10000";
dt.Rows.Add(rowC1);
return dt;
}
private void button1_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
dt= getdata();
// Find distinct projects
var distinctProjects = (from r in dt.AsEnumerable()
select r["ProjectName"]).Distinct().OrderBy(project => project);
// Get all amounts to tally later for the All Total entry
var allEntries = from r in dt.AsEnumerable()
select r["SourceAmount"];
// Loop through distinct project list and add project subtotal row to table
foreach (var p in distinctProjects)
{
var amt = from r in dt.AsEnumerable()
where r["ProjectName"] == p
select r["SourceAmount"];
DataRow dr = dt.NewRow();
dr["ProjectName"] = p + " Sub Total:";
dr["SourceAmount"] = amt.Sum(x => Convert.ToDecimal(x));
dt.Rows.Add(dr);
}
// Sort table so the sub totals fall under the project it belongs to
DataView dv = dt.DefaultView;
dv.Sort = "ProjectName ASC, Source ASC";
dt = dv.ToTable();
// Create and add the final total row
DataRow finalTotal = dt.NewRow();
finalTotal["ProjectName"] = "All Total:";
finalTotal["SourceAmount"] = allEntries.Sum(x => Convert.ToDecimal(x));
dt.Rows.Add(finalTotal);
// Display correct results with message box
foreach (DataRow r in dt.Rows)
{
MessageBox.Show(
r["ProjectName"].ToString() + " " +
r["Source"].ToString() + " " +
r["SourceAmount"].ToString()
);
}
}
}
}
Output:
Dataset Input:
Dataset OUTPUT:
No comments:
Post a Comment