One of the most common questions in the Forum is: "How do I display the total of columns in the DataGrid ?". I personally provided examples for this issue multiple times. Code Therefore, I want to provide such a guide in the title of dotnetjunkies. In this guide, you will learn how to program and calculate the values of a column in the DataGrid and display the total values in the footer of the DataGrid. The sample code for download in this Guide includes C # and Visual Basic. net.
The final result of this Guide looks like this:
We can see that:
The DataGrid in the screen image used above is a very typical DataGrid. There are many attributes that control the appearance of the DataGrid. It uses two boundcolumns to operate data, but this is not the most important. To do this well, it is really important to use the DataGrid. onitemdatabound event. This event will trigger binding a record to the DataGrid each time. You can create an event processing event to record the operation data. In this case, you will get the total value of the price column at run time.
The footer refers to the last row of the data range. When this line is limited, you can get the running statistical value of the price column during event sentence processing.
Implementation:
First, let's find a way to operate the web form output. In this guide, you will use a web form (calctotals. aspx) and a class code file (calctotals. aspx. CS ). The intention of this Guide is that the class code will be compiled using the just-in-time compiler. Here is the code for calctotals. aspx:
<% @ Page inherits = "MyApp. calctotals" src = "20034731t0101. aspx. cs" %> Autogeneratecolumns = "false" cellpadding = "4" cellspacing = "0" borderstyle = "solid" borderwidth = "1" gridlines = "NONE" bordercolor = "black" itemstyle-font-name = "verdana" itemstyle-font-size = "9pt" headerstyle-font-name = "verdana" headerstyle-font-size = "10pt" headerstyle-font-bold = "true" headerstyle-forecolor = "white" headerstyle-backcolor = "blue" footerstyle-font-name = "verdana" footerstyle-font-size = "10pt" footerstyle-font-bold = "true" footerstyle-forecolor = "white" footerstyle-backcolor = "blue" onitemdatabound = "mydatagrid_itemdatabound" showfooter = "true"> Itemstyle-horizontalalign = "right" headerstyle-horizontalalign = "center"/> |
In a web form, you use @ page to directly declare the class code inherited by this page. The src attribute specifies that the class code will be compiled using the JIT compiler. Most code style declarations in web forms are used to make the DataGrid look better.
One of the last specified attributes is the onitemdatabound attribute. This event will be triggered when the onitemdatabound event occurs.
The DataGrid (mygrid) in the web form contains two boundcolumns: one is the title and the other is the price. The title and price columns of the titles table in the pubs database (SQL Server) are displayed.
Ignore code definitions
Class Code will be used everywhere. In the class code, you can operate on two events: the page_load event and the mygrid_onitemdatabound event. There is also a private method calctotal, which is used to easily complete the mathematical calculation of runtime statistics.
The starting part of the basic structure block of the class code:
Using system; Using system. Web; Using system. Web. UI; Using system. Web. UI. webcontrols; Using system. Web. UI. htmlcontrols; Using system. Data; Using system. Data. sqlclient;Namespace MyApp { Public class calctotals: Page { Protected DataGrid mygrid; Private double runningtotal = 0; } } |
In the basic structure of the class code, you must use the relevant statements to import the namespace ). In the class declaration, you declare two variables. One is the variable mapped to the DataGrid (mygrid) control of the web form in the class code; one is the double precision value used to operate the ROW statistics in the price column of the DataGrid.
Page_load event
In the page_load event, all you need to do is connect to SQL Server and execute a simple sqlcommand. You have obtained all the title and price data with a price value greater than 0. You use the sqlcommand. executereader method to return a sqldatareader and bind it directly to the DataGrid (mygrid ).
Protected void page_load (Object sender, eventargs E) { Sqlconnection myconnection = new sqlconnection ("Server = localhost; database = pubs; uid = sa; Pwd =;"); // create an SQL connection Sqlcommand mycommand = new sqlcommand ("select title, price from titles where price> 0", myconnection); // create an SQL commandTry { Myconnection. open (); // open the database connection Mygrid. datasource = mycommand. executereader (); // specify the data source of the DataGrid. Mygrid. databind (); // bind data to the DataGrid Myconnection. Close (); // close the data connection } Catch (exception ex) { // Capture errors Httpcontext. Current. response. Write (ex. tostring ()); } } |
Calctotals Method
The calctotals method is used to process the runningtotal variable. This value is passed as a string. You need to resolve it to the double-precision type, and then the runningtotal variable becomes the double-precision type.
Private void calctotal (string _ price) { Try { Runningtotal + = double. parse (_ price ); } Catch { // Capture errors } } |
Mygrid_itemdatabound event
The mygrid_itemdatabound event is called when each row in the data source is bound to the DataGrid. In this event processing, you can process each row of data. Here your purpose is to call the calctotals method and pass the text from the price column, format the price column of each row with the amount type, and display the value of runningtotal In the footer row.
Public void mydatagrid_itemdatabound (Object sender, datagriditemeventargs E) { If (E. Item. itemtype = listitemtype. Item | E. Item. itemtype = listitemtype. alternatingitem) { Calctotal (E. Item. cells [1]. Text ); E. Item. cells [1]. Text = string. Format ("{0: c}", convert. todouble (E. Item. cells [1]. Text )); } Else if (E. Item. itemtype = listitemtype. footer) { E. Item. cells [0]. Text = "Total "; E. Item. cells [1]. Text = string. Format ("{0: c}", runningtotal ); } } |
In the mygrid_itemdatabound event handle, you must first use listitemtype to determine whether the current datagriditem is a data item or an alternatingitem row. If it is a data item, you call calctotals and pass the value of the price column to it as a parameter. Then, you format and color the price column in the amount format.
If the datagriditem is a footer, runningtotal can be displayed in the amount format.
Summary
in this Guide, you learned how to use the DataGrid. onitemdatabound event to collect statistics on a column of the DataGrid during running. With this event, you can create a total of columns and color the footer of the row in the DataGrid.