ASP. NET DataGrid Control Data grouping operation

Source: Internet
Author: User

ASP. NET DataGrid Control Data grouping operation

The following SQL command Selects all orders issued by all customers in a given year. Only the total price of all items in each order is displayed.

 
 
  1. SELECT o.customerid, od.orderid, SUM(od.quantity*od.unitprice) AS price   
  2. FROM Orders o, [Order Details] od  
  3. WHERE Year(o.orderdate) = @TheYear AND od.orderid=o.orderid  
  4. GROUP BY o.customerid, od.orderid  
  5. ORDER BY o.customerid 

In the T-SQL language, the group by clause of the SELECT statement provides the ability to add predefined summary rows to the result setWITH ROLLUPClause. Of course, such a summary row has the layout of all other columns, but the content of each column can be customized to some extent. The following statement explains how to modify the preceding command so that it can use the summary line.

 
 
  1. DECLARE @TheYear int 
  2. SET @TheYear = 1998  
  3.  
  4. SELECT   
  5.     CASE GROUPING(o.customerid) WHEN 0   
  6. THEN o.customerid ELSE '(Total)' END AS MyCustomerID,   
  7.     CASE GROUPING(od.orderid) WHEN 0   
  8. THEN od.orderid ELSE -1 END AS MyOrderID,   
  9.     SUM(od.quantity*od.unitprice) AS price  
  10. FROM Orders o, [Order Details] od  
  11. WHERE Year(orderdate) = @TheYear AND od.orderid=o.orderid  
  12. GROUP BY o.customerid, od.orderid WITH ROLLUP 
  13. ORDER BY o.customerid, price  

If you copy the code snippet and paste it into the SQL query analyzer, you will see the content as shown in.

ASP. NET DataGrid Control: with rollup clause adds the summary row to the result set.

GROUPINGIs a T-SQL aggregate function that works with ROLLUP in the body of the group by clause. Add a new column to the result set using the GROUPING operator. If the row has been added by the ROLLUP operator and therefore becomes a summary row, the new column will contain the value 1. Otherwise, the column contains a value of 0. UseCASE... WHEN... ENDStatement can combine the new column with the group column.

In the preceding example,MyCustomerIDColumns are included in all rows created for grouping.CustomerIDThe column value and the string "(Total )". Similarly, when this row represents a small timer,MyOrderIDThe column contains the order ID and-1.

To summarize data, SQL Server also provides several options, for example,WITH CUBEOperator andCOMPUTEClause. As you might imagine, although the functionality of one option is in a way that matches the functionality of another option, all these options are not exactly equivalent. In particular,WITH CUBEA summary row is generated for each possible combination of the group and the sub-group in the result set. WhileWITH ROLLUPGrouping is performed according to the specified sequence of grouping columns. Finally,COMPUTESQL Server 2000 only supports backward compatibility .)WITH ROLLUPThe difference is that it returns multiple result sets and is not as efficient as ROLLUP when processed by the query optimizer.

ASP. NET DataGrid Control: displays grouped data

When bound to the DataGrid Control, the result set returned by the SQL command looks as shown in.

ASP. NET DataGrid Control: result set displayed through the DataGrid Control

The DataGrid Control Used in the example application is declared as follows:

 
 
  1. < asp:DataGrid id="grid" runat="server"   
  2. AutoGenerateColumns="false" 
  3. AllowPaging="true" PageSize="15" 
  4. Font-Size="xx-small" 
  5. CellSpacing="0" CellPadding="4" GridLines="both" 
  6. BorderStyle="solid" BorderColor="skyblue" BorderWidth="1"   
  7. OnItemCreated="ItemCreated" 
  8. OnPageIndexChanged="PageIndexChanged"> 
  9.  
  10. < headerstyle backcolor="skyblue" font-size="9pt" font-bold="true" /> 
  11. < itemstyle backcolor="#eeeeee" /> 
  12. < pagerstyle backcolor="skyblue" font-name="webdings"   
  13. font-size="10pt" PrevPageText="3" NextPageText="4" /> 
  14.  
  15. < Columns> 
  16. < asp:BoundColumn DataField="MyCustId" HeaderText="Customer" /> 
  17. < asp:BoundColumn DataField="MyOrderId" HeaderText="Order #" /> 
  18. < asp:BoundColumn DataField="price" HeaderText="Amount"   
  19. DataFormatString="{0:c}"> 
  20. < itemstyle horizontalalign="right" /> 
  21. < /asp:BoundColumn> 
  22. < /Columns> 
  23. < /asp:DataGrid> 

UseWITH ROLLUPThe data source obtained by the operator already contains all the information necessary to generate a valid report. You may have noticed that this statement adds a top line that contains the total number of orders issued by all customers. In useWITH ROLLUPIf you modify the order of grouping rows, the number and structure of the rows may change significantly. This additional line is the result of using the specific syntax. If you do not need this information, you only need to delete it from the result set before binding. Alternatively, you can move the row to the bottom of the dataset.

The code shown below demonstrates how to execute the rollup statement. The parameter read from the text box is the year to consider. The result set is temporarily stored inDataSetObject. In this example applicationSessionCache in slotDataSetObject. In the actual environment, this should be an important choice. TypicallySessionAny byte in has a reason to be there.

 
 
  1. private DataSet PhysicalDataRead()  
  2. {  
  3. String strCnn = "SERVER=localhost;DATABASE=northwind;UID=sa;";  
  4. SqlConnection conn = new SqlConnection(strCnn);  
  5.  
  6. // Command text using WITH ROLLUP  
  7. StringBuilder sb = new StringBuilder("");  
  8. sb.Append("SELECT ");  
  9. sb.Append("  CASE GROUPING(o.customerid) WHEN 0 ");  
  10. sb.Append("    THEN o.customerid ELSE '(Total)' END AS MyCustID, ");  
  11. sb.Append("  CASE GROUPING(od.orderid) WHEN 0 ");  
  12. sb.Append("    THEN od.orderid ELSE -1 END AS MyOrderID, ");  
  13. sb.Append("  SUM(od.quantity*od.unitprice) AS price ");  
  14. sb.Append("FROM Orders o, [Order Details] od ");  
  15. sb.Append("WHERE Year(orderdate)=@nYear AND od.orderid=o.orderid ");  
  16. sb.Append("GROUP BY o.customerid, od.orderid WITH ROLLUP ");  
  17. sb.Append("ORDER BY o.customerid, price");  
  18. String strCmd = sb.ToString();  
  19. sb = null;  
  20.  
  21. SqlCommand cmd = new SqlCommand();  
  22. cmd.CommandText = strCmd;  
  23. cmd.Connection = conn;     
  24. SqlDataAdapter da = new SqlDataAdapter(strCmd, strConn);  
  25. da.SelectCommand = cmd;  
  26.  
  27. // Set the "year" parameter  
  28. SqlParameter p1 = new SqlParameter("@nYear", SqlDbType.Int);  
  29. p1.Direction = ParameterDirection.Input;  
  30. p1.Value = Convert.ToInt32(txtYear.Text);  
  31. cmd.Parameters.Add(p1);  
  32.  
  33. DataSet ds = new DataSet();  
  34. da.Fill(ds, "Orders");  
  35. return ds;  
  36. }  

To make the summary row clearly displayed on the page of the grid, you need to change the style and layout of the summary row. This can be found inItemCreatedCompleted in the event handler. The design idea is to check the order ID to detect the summary rows, and then modify the layout and style of cells. In the result set, the characteristic of the summary row is that the Order ID is-1. Value-1 is the value of any statement used.

 
 
  1. CASE GROUPING(od.orderid) WHEN 0 THEN od.orderid ELSE -1 END AS MyOrderID  

If notOrderidColumn usageGROUPINGFor a summary row, the column value is NULL.

The preceding section summarizes how to use the ASP. NET DataGrid Control to group data.

  1. What is the ASP. NET DataGrid Control: Fully templated Grid
  2. Comparison between ASP. NET's GridView and DataGrid controls
  3. . NET beginner's Guide: easily customize the DataGridView Control
  4. C # Some common operations on the DatagridView
  5. ASP.net exports the DataGrid content as an excel file

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.