Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to configure GridView footer to display statistics in ASP.NET 2.0

2025-04-06 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article is about how to configure GridView footers to display statistics in ASP.NET 2.0. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.

Introduction

In addition to knowing the unit price, inventory, and order of the product, and ranking it by rank, users may also be interested in statistical information, such as average price, total inventory, and so on. These statistics are often displayed in the bottom statistical row of the report. The GridView control can contain a footer row, and we can programmatically insert statistics into its cells. This task gives us the following three challenges:

1. Configure GridView to display its footer line

two。 Determine the statistics. That is, how should we calculate the average price and the total inventory?

3. Insert statistics into the appropriate cell in the footer row

In this tutorial, we will see how to overcome these challenges. In addition, we will create a page with a drop-down box listing all "categories", and select a "category" to display this category of products in GridView. GridView contains a footer line that shows the average price, total inventory, and total order for such products.

Figure 1: statistics are displayed in the footer row of GridView

Because of the master / slave interface from Category to Product, all this section builds on the concepts discussed in the previous section, "Master / Slave filtering with DropDownList". If you haven't read that section, you'd better go and see it before continuing with this section.

Section 1: add the Category drop-down box and the Product GridView

Before adding footer rows to GridView, let's simply create a master / slave report. Once we have completed this first step, we can take a look at how to add statistics.

First open the SummaryDataInFooter.aspx page in the CustomFormatting folder. Add a DropDownList control and set its ID to Categories. Then, click "Select data Source (Choose DataSource)" on the smart tag of the DropDownList, add a new ObjectDataSource control that calls the GetCategories () method of the CategoriesBLL class, and name the ObjectDataSource CategoriesDataSource.

Figure 2: adding a new ObjectDataSource control named CategoriesDataSource

Figure 3: make this ObjectDataSource control call the GetCategories () method of the CategoriesBLL class

After configuring ObjectDataSource, the wizard returns us to DropDownList's data source configuration wizard, where we can specify which fields need to be displayed and which fields should be the value of DropDownList's ListItem. We display the CategoryName field and take CategoryID as the value.

Figure 4: using CategoryName and CategoryID as the text and value of ListItem, respectively

Now we have a DropDownList in the system that can list categories. Now we need to add a GridView that lists the products according to the selected category. Before we do that, however, let's take a moment to check the "enable automatic postback (Enable AutoPostBack)" check box in DropDownList's smart tag. As we discussed in the previous section "using DropDownList for master / slave filtering lidong6", after setting the AutoPostBack property of DropDownList to true, the page will post back whenever the value of DropDownList changes. This allows you to refresh the GridView to display the newly selected category of products. If the AutoPostBack property is set to false (the default), changing the category will not cause a postback, so the product list will not be refreshed.

Figure 5: check the "enable automatic postback" check box in the smart tag of DropDownList

Add a GridView control to the page so that the product can be displayed according to the selected category. Set the ID of this GridView to ProductsInCategory and bind it to a new ObjectDataSource called ProductsInCategoryDataSource.

Figure 6: add a new ObjectDataSource named ProductsInCategoryDataSource

Configure this ObjectDataSource to call the GetProductsByCategoryID (categoryID) method of the ProductsBLL class.

Figure 7: make this ObjectDataSource call the GetProductsByCategoryID (categoryID) method

Because the GetProductsByCategoryID (categoryID) method requires a parameter, in the last step of the wizard, we can specify the data source for the parameter value. In order to display the product based on the category selected for display, this parameter should be obtained from the Categories drop-down box.

Figure 8: get the categoryID parameter from the Catefories drop-down box

After completing the wizard, the GridView will contain some BoundField corresponding to each attribute of the product. Let's clean up the BoundField and leave the ProductName, UnitPrice, UnitsInStock, and UnitsOnOrder to display. Then feel free to add some field-level settings to the rest of the BoundField (such as formatting UnitPrice into currency). After making these changes, the declaration tag for the GridView should look like this:

Now we have a fully functional master / slave report that displays the name, unit price, inventory and order quantity of the relevant product according to the selected category.

Fig9: the current effect (translator's note: it is estimated that there is a mistake here in the original text, which is the same as in figure 8. The original text here is "Figure 9: Get the categoryID Parameter Value from the Selected Categories DropDownList", and the original text of figure 8 is "Figure 8: Get the categoryID Parameter Value from the Selected Categories DropDownList")

Step 2: display the footer in GridView

The GridView control can display header and footer rows. Whether these rows are displayed or not depends on the ShowHeader and ShowFooter properties, respectively, and by default, the value of ShowHeader is true and the value of ShowFooter is false. To display the footer line, we simply set the ShowFooter property to true.

Figure 10: set the ShowFooter property of GridView to true

Each field defined in GridView has a corresponding cell in the footer row, but these cells are empty by default. Take a moment to go to the browser and see what we've done. Because we set the ShowFooter property of GridView to true, GridView now contains an empty footer line.

Figure 11: GridView now has a footer line

The footer line in figure 11 is not obvious because its background is white. Let's create a CSS class called FooterStyle in Styles.css, use it to specify a crimson background, and configure the GridView.skin skin file (Skin file) in the DataWebControls theme to assign this CSS class to the CssClass property of the FooterStyle of this GridView. If you need to review the skins and topics, please refer to "displaying data using ObjectDataSource".

First add the following CSS class to Styles.css:

.FooterStyle {background-color: # a33; color: White; text-align: right;}

The CSS class FooterStyle is the same as the HeaderStyle class, except that the background color of HeaderStyle is a little deeper and the text is shown in bold. In addition, the footer text is right-aligned, while the header text is centered. Then, to associate this CSS class to the footer of each GridView, open the GridView.skin file in the DataWebControls theme and set the CssClass property of the FooterStyle. After this addition, the tag code for the file should look like this:

As shown in the screenshot below, this change makes the footer clearly displayed.

Figure 12: the footer of GridView now has a red background color

Step 3: calculate the statistics

After showing the footer of GridView, the next challenge for us is how to calculate the statistics. There are two ways to calculate statistics:

1. With a SQL query-- we can issue an additional query to the database to calculate statistics for a particular category. SQL contains a series of aggregate functions, and the GROUP BY clause specifies what data should be counted based on. The following SQL query will return the information we need:

SELECT CategoryID, AVG (UnitPrice), SUM (UnitsInStock), SUM (UnitsOnOrder) FROM ProductsWHERE CategoryID = categoryIDGROUP BY CategoryID

Of course, you may not like to execute this query directly in the SummaryDataInFooter.aspx page, but you want to create a method to do it in ProductsTableAdapter and ProductsBLL.

two。 Because this information has been added to GridView, it can be calculated directly-- as discussed in "Custom formatting based on data," after GridView's data binding, GridView's RowDataBound event handling method is executed once when each row of data is added. Once we have created an event handling method for this event, we can maintain a cumulative total value. After the last row of data is bound to DataGrid, we have a total value and the information that we need to calculate the average.

Generally speaking, I prefer the second method because it saves a round trip to the database, and to achieve this effect, you need to implement statistical functions in the data access layer and the business logic layer, but then again, in fact, both methods work. In this tutorial, let's use the second approach and use the RowDataBound event handling method to record this cumulative total.

To create a new RowDataBound event handler for GridView, you can select GridView in the designer, then click the icon with the lightning symbol in the properties window, find the RowDataBound event and double-click it. This adds a new event handling method called ProductsInCategory_RowDataBound to the post-code class of the SummaryDataInFooter.aspx page.

Protected void ProductsInCategory_RowDataBound (object sender, GridViewRowEventArgs e) {}

In order to maintain a cumulative total, we need to define some variables outside the event handling method. Create the following four page level variables:

_ totalUnitPrice, type is decimal

_ totalNonNullUnitPriceCount, type is int

_ totalUnitsInStock, type is int

_ totalUnitsOnOrder, type is int

Then, write some code in the RowDataBound event handling method so that each row of data can increment the values of these variables.

/ / Class-scope, running total variables...decimal _ totalUnitPrice = 0mint _ totalNonNullUnitPriceCount = 0int _ totalUnitsInStock = 0poliint _ totalUnitsOnOrder = 0poliprotected void ProductsInCategory_RowDataBound (object sender, GridViewRowEventArgs e) {if (e.Row.RowType = = DataControlRowType.DataRow) {/ / Reference the ProductsRow via the e.Row.DataItem property Northwind.ProductsRow product = (Northwind.ProductsRow) ((System.Data.DataRowView) e.Row.DataItem) .Row; / / Increment the running totals (if they are not NULL!) If (! product.IsUnitPriceNull ()) {_ totalUnitPrice + = product.UnitPrice; _ totalNonNullUnitPriceCount++;} if (! product.IsUnitsInStockNull ()) _ totalUnitsInStock + = product.UnitsInStock; if (! product.IsUnitsOnOrderNull ()) _ totalUnitsOnOrder + = product.UnitsOnOrder;}}

In the RowDataBound event handling method, we should first make sure that we are operating on a DataRow. Once this is determined, the Northwind.ProductsRow instance in e.Row that has just been bound to the GridViewRow object can be assigned to the product variable. The cumulative totals are then increased by the relevant values of the current product (of course, we should make sure that they do not contain a database null value). We also record the cumulative total of UnitPrice and the number of non-empty UnitPrice records, because the average price is the quotient of these two numbers.

Step 4: display statistics in the footer

After calculating the statistics, the final step is to display it on the footer of GridView. Similarly, this task can also be accomplished through the RowDataBound event handling method. Recall that the RowDataBound event handling method is triggered when each row is bound to GridView, and the footer row is no exception. Therefore, we can extend our event handling method so that it can display data in the footer line with the following code:

Protected void ProductsInCategory_RowDataBound (object sender, GridViewRowEventArgs e) {if (e.Row.RowType = = DataControlRowType.DataRow) {... Increment the running totals.} else if (e.Row.RowType = = DataControlRowType.Footer) {. Display the summary data in the footer...}}

Because the footer row is added to the GridView after all the data rows have been added, we can believe that the cumulative totals have been calculated before the statistics are displayed in the footer. The final step is to put these values in the cell in the footer.

To display text in a specific cell in the footer, you can use use e.Row.Cells [index]. Text = value, where the index of the cell starts at 0. The following code calculates the average price (the total price divided by the quantity of the product) and displays it in the appropriate cell in the GridView footer together with inventory and order quantity.

Protected void ProductsInCategory_RowDataBound (object sender, GridViewRowEventArgs e) {if (e.Row.RowType = = DataControlRowType.DataRow) {... Increment the running totals...} else if (e.Row.RowType = = DataControlRowType.Footer) {/ / Determine the average UnitPrice decimal avgUnitPrice = _ totalUnitPrice / (decimal) _ totalNonNullUnitPriceCount; / / Display the summary data in the appropriate cells e.Row.Cells [1] .Text = "Avg.:" + avgUnitPrice.ToString ("c"); e.Row.Cells [2] .Text = "Total:" + _ totalUnitsInStock.ToString () E.Row.Cells [3] .text = "Total:" + _ totalUnitsOnOrder.ToString ();}}

Figure 13 shows what the report looks like after adding this code. Notice how ToString ("c") formats the statistics of average prices in monetary form.

Figure 13: the current effect (translator's note: it is estimated that there is another mistake in the original text, which is the same as in figure 12. The original text here is "Figure 13: The GridView's Footer Row Now Has a Reddish Background Color", as shown in figure 12. The original text here is "Figure 13: The GridView's Footer Row Now Has a Reddish B. The original text is" Figure 12: The GridView's Footer Row Now Has a Reddish Background Color ")

Thank you for reading! This is the end of the article on "how to configure the GridView footer to display statistics in ASP.NET 2.0". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, you can share it for more people to see!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 210

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report