Asp. NET Add Total field for DataGrid _ Practical Tips

Source: Internet
Author: User
One of the most common questions in the forum is: "How do I display column totals in a DataGrid?" ”。 I have provided sample code for this issue many times myself, so I would like to provide a guide in the title of Dotnetjunkies. In this guide you will learn how to program the values of a column in a DataGrid and display its aggregate values in the footer of the DataGrid. The examples for downloading in this guide include C # and Visual Basic.NET two of code.

The final result of this guide looks like this:


As you can see from the diagram above:

The DataGrid in the screen image used above is a very typical DataGrid. There are many properties that control the appearance of the DataGrid, and it uses two boundcolumns to manipulate the data, but that is not the most important. It is really important to do this job by using the Datagrid.onitemdatabound event. This event will trigger each time a record is bound to the DataGrid. You can create an event handler for this event to manipulate the data record. In this case, you will get the aggregate value of the runtime Price column.

The footer refers to the last line of data range. When this line is qualified, you can get the run-time statistics of the price column in the event sentence processing.

   Implement

First, let's find a way to manipulate Web forms output. In this guide, you will use a Web form (calctotals.aspx) and a Class code file (CalcTotals.aspx.cs). The intent of this guide is that class code will be compiled using the Just-In-Time compiler. Here is the code for calctotals.aspx:

<%@ Page inherits= "myapp.calctotals" src= "20010731t0101.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 the @ Page to directly declare the class code that the page inherits. The SRC attribute indicates that the class code will compile using the JIT compiler. Most code style declarations in Web forms are used to make the DataGrid look better.

One of the last properties specified is the Onitemdatabound property. This event will be triggered when the Onitemdatabound event occurs.

The DataGrid (Mygrid) in a Web form contains two boundcolumns, one is Title, and the other is price. The title and price columns of the Titles table in the Pubs database (SQL Server) are displayed here.

   Ignore definition of code

The class code will be used everywhere. In the class code, you can manipulate two events: the Page_Load event and the Mygrid_onitemdatabound event. There is also a private method Calctotal, which is used to simply complete the mathematical operation of Run-time 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 import the namespace (namespace) using the relevant statements. In the class declaration, you declare two variables, a variable that maps the DataGrid (Mygrid) control of a Web form in class code, and a double value that is used to manipulate the run-time statistics in the price column of the DataGrid.

   Page_Load Events

In the Page_Load event, all you have to do is connect to SQL Server and perform a simple SqlCommand. You have obtained the title and price data for all price values >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 SQL connection
SqlCommand mycommand = new SqlCommand ("Select title, price to Titles where price > 0", MyConnection);//Create SQL command

Try
{
Myconnection.open ()//Open database connection
Mygrid.datasource = Mycommand.executereader ();//Specify Data source for DataGrid
Mygrid.databind ()//bind data to DataGrid
Myconnection.close ()//Close data connection
}
catch (Exception ex)
{
Catch error
HttpContext.Current.Response.Write (ex. ToString ());
}
}

   Calctotals Method

The Calctotals method is used to process runningtotal variables. This value is passed as a string. You need to parse it into a double, and then the runningtotal variable becomes a double-precision type.

private void Calctotal (string _price)
{
Try
{
RunningTotal + + double.parse (_price);
}
Catch
{
Catch error
}
}

  Mygrid_itemdatabound Events

The Mygrid_itemdatabound event is invoked when each row in the data source is bound to a DataGrid. In this event processing, you can process each row of data. Your purpose here is that you will need to call the Calctotals method and pass the text from the Price column, format the price column for each row with the amount type, and display the RunningTotal value 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 first have to use ListItemType to determine whether the current DataGridItem is a data item or a AlternatingItem row. If it is a data item, you call Calctotals and pass the value of the price column to it as an argument, and then you format and color the price column in amount format.

If DataGridItem is a footer, you can display runningtotal in amount format.

   Summary

In this guide, you learned how to use the Datagrid.onitemdatabound event to count the columns of a DataGrid at run time. With this event, you can create totals for a column and color the footer of the DataGrid row.
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.