I see that my post here about creating Summary rows(sub totals) in a Silverlight datagrid is getting a lots of hits. So, I have decided to write another post on getting Grand total in a Silverlight datagrid.
Let us get in to the action.
The below application that we are going to build is going to display Datagrid with data about the revenues of each Restaurant and finally the total Revenue value of all the Restaurants.
1. Create a Silverlight project. Add a DataGrid in to the MainPage.xaml.
2. Create a class called Revenue and add Properties in to it like Restaurant and Revenue as shown below.
<br /><%%KEEPWHITESPACE%%> public class Revenues<br /><%%KEEPWHITESPACE%%> {<br /><%%KEEPWHITESPACE%%> public string Restaurant { get; set; }<br /><%%KEEPWHITESPACE%%> public decimal Revenue { get; set; }<br /><%%KEEPWHITESPACE%%> }<br />3. Now, lets use ObservableCollection and add data to our Revenue class created above through ObservableCollection in the MainPage Constructor .
ObservableCollection(NameSpace : System.Collections.ObjectModel)<br /><%%KEEPWHITESPACE%%> OCRevenues.Add(new Revenues() { Restaurant = "McDonalds", Revenue = 3000 });<br /><%%KEEPWHITESPACE%%> OCRevenues.Add(new Revenues() { Restaurant = "KFC", Revenue = 1000 });<br /><%%KEEPWHITESPACE%%> OCRevenues.Add(new Revenues() { Restaurant = "Pizza Hut", Revenue = 12000 });<br />4. Now, in order to calculate the Grand total of the values in the Revenues column, put the below line of code.
<br /><%%KEEPWHITESPACE%%> OCRevenues.Add(new Revenues() { Restaurant = "Grand Total", Revenue = OCRevenues.Sum(o => o.Revenue) });<br />5. In the above line we are adding a new data item to OCRevenues ObservableCollection with Restaurant value as “Grand Total”, and the Revenue value to be the sum of all the Revenue values in the OCRevenues using lambda expression.
6. Build and compile the application, you will get the output as shown below.
7. Let us make it little a bit more attractive by coloring the Grand Total row alone grey, so that it gets highlighted.
8. This can be achieved by attaching a LoadingRow event to the DataGrid. So, attach LoadingRow event to the DataGrid and then in the event handler write the following code.
<br /><%%KEEPWHITESPACE%%> private void dgGrandTotal_LoadingRow(object sender, DataGridRowEventArgs e)<br /><%%KEEPWHITESPACE%%> {<br /><%%KEEPWHITESPACE%%> Revenues revenueDetails = e.Row.DataContext as Revenues;<br /><br /><%%KEEPWHITESPACE%%> if (revenueDetails.Restaurant.Contains("Grand Total"))<br /><%%KEEPWHITESPACE%%> {<br /><%%KEEPWHITESPACE%%> e.Row.Background = new SolidColorBrush(Colors.DarkGray);<br /><%%KEEPWHITESPACE%%> }<br /><%%KEEPWHITESPACE%%> }<br />9. In the above coding we are checking if the value of the Restaurant property in the current row is “Grand Total” and then giving the row a Dark grey background. Once you build and execute the application you will get an output as shown below.
Advertisements