I am using Aggregate="sum", but one of my rows contains years and should not be aggregated.
Is there a way?
1 Answer, 1 is accepted
0
Vasko
Telerik team
answered on 27 Oct 2023, 12:48 PM
Hello David,
To achieve the desired behavior, you can use Custom Aggregate functionality.
For example, you can change the Aggregate property to "Custom", instead of "Sum", because in the given scenario you'd want to exclude the date from the end result. I've prepared a sample code snippet that demonstrates the outcome of this approach:
The DataType needs to be a string so the custom aggregation works. The markup of the Grid used in this example is the following:
In the backend part of the code, the Grid is bound to some sample data:
private DataTable OrdersTable() // Creating a collumn with rows of numeric and DateTime values
{
DataTable dt = new DataTable();
dt.Columns.Add(new DataColumn("MyField", typeof(string)));
for (int i = 0; i < 5; i++)
{
int index = i + 1;
DataRow row = dt.NewRow();
if (index == 2 || index == 4)
{
row["MyField"] = DateTime.Now.Date.ToString();
}
else
{
row["MyField"] = index.ToString();
}
dt.Rows.Add(row);
}
return dt; // This will return a test grid with one column with 5 rows, 2 of which are dates
}
protectedvoidRadGrid1_NeedDataSource(object sender, GridNeedDataSourceEventArgs e)
{
RadGrid grid = sender as RadGrid;
DataTable sourceData = OrdersTable();
grid.DataSource = sourceData;
double sum = 0;
foreach (DataRow row in sourceData.Rows)
{
double numericValue;
if (double.TryParse(row["MyField"].ToString(), out numericValue)) // If the value in the row is a number, add it to the aggregated sum.
{
sum += Convert.ToDouble(row["MyField"]);
}
}
grid.MasterTableView.GetColumn("MyField").FooterText = "Sum: " + sum.ToString();
}
With the above code, we achieve the following:
After setting the data source for the RadGrid, we loop through each data row and check if its value is of type double (or if it's a numeric value) using double.TryParse().
We add the value to our aggregate sum if it is a number.
Finally, we set the FooterText of the column to display our custom aggregate.
For more information about aggregation, I suggest taking a look at the following articles: