Displaying summary information in GridView
Summarizing data in the GridView:
In this article we are going to display product information in the Grid View and see how to display summary information in GridView. We are going to use the Footer Row of Grid View to display the Total.
In this article we are going to see how to display summary information in GridView. We are going to use the Footer Row of Grid View to display the Total.
Below are the steps which we are going to follow:
1. Drag and drop gridview in the .aspx page and set ShowFooter property of GridView to true. Rename the GridView to "gvData". Footer row is used to display the summary information. Additionally double click in the events tab of grid view on the RowDataBound event to generate the rowdataevent.
In this event we are going to write the code to summarize the data.
<asp:GridView ID="gvData" runat="server" onrowdatabound="gvData_RowDataBound"
ShowFooter="True">
</asp:GridView>
2. In Page_Load event of the webpage write the code to create a datatable and add data to it. Bind this data to gridview as shown below:
protected void Page_Load(object sender, EventArgs e)
{
DataTable dt = new DataTable("Product");
dt.Columns.Add("Product Id", typeof(String));
dt.Columns.Add("Product Name", typeof(String));
dt.Columns.Add("Quantity", typeof(int));
dt.Columns.Add("Price", typeof(decimal));
DataRow dr = dt.NewRow();
dt.Rows.Add(1, "Product1", 5, 40.0);
dt.Rows.Add(2, "Product2", 2, 30.0);
dt.Rows.Add(3, "Product3", 15, 400.0);
dt.Rows.Add(4, "Product4",6, 90.0);
gvData.DataSource = dt;
gvData.DataBind();
}
3. When data is binded to gridview row by row RowDataBound event of Gridview is fired. That means each row of datatable is binded to gridview. If the rowtype is DataRow i.e., if the data is being binded to gridview. From every row we are getting the quantity and price and aggregating it to calculate the total of quantity and price field values respectively. Finally if the RowType is Footer, We are going to dynamically create two label controls one each for quantity and price and add it to respective cells of GridView in the Footer Row.
int quantity = 0;
decimal price = 0;
protected void gvData_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
//Get the reference to DataRow being binded to grid view.
DataRowView drv = (DataRowView) e.Row.DataItem;
//Calculate total of quantity and price.
quantity += (int) drv["Quantity"];
price += (decimal)drv["Price"];
}
if (e.Row.RowType == DataControlRowType.Footer)
{
Label lblQuantity = new Label();
Label lblPrice = new Label();
//Set the Total Quantity and Total Price to the respective labels.
lblQuantity.Text = quantity.ToString();
lblPrice.Text = price.ToString();
//Add the Quantity and Price labels in the Footer row.
e.Row.Cells[2].Controls.Add(lblQuantity);
e.Row.Cells[3].Controls.Add(lblPrice);
}
}