Trong mẹo lập trinh hôm nay chúng tôi sẽ hướng dẫn các bạn cách làm thế nào để chương trình tự động tính tổng của một cột trong DataGrid, và hiển thị tổng trong footer của DataGrid.
Bạn sẽ dùng một Web Form (calcTotals.aspx) và một đoạn code sau lớp tập tin này (calcTotals.aspx.cs)
Sau đây là code calcTotals.aspx:
<%@ Page Inherits=''myApp.calcTotals'' Src=''20010731T0101.aspx.cs'' %>
<body bgcolor=''white''>
<aspataGrid id=''MyGrid'' runat=''server''
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''>
<asp:BoundColumn HeaderText=''Title'' DataField=''title'' />
<asp:BoundColumn HeaderText=''Price'' DataField=''price''
ItemStyle-HorizontalAlign=''Right''
HeaderStyle-HorizontalAlign=''Center'' />
Trong Web Form bạn dùng dấu @ để trang sử dụng code trong phần khai báo. thuộc tính SRC chỉ code sẽ được biên dịch sử dụng bộ biên dịch JIT.
Code trong lớp sẽ xử lý 2 sự kiện Page_Load event và OnItemDataBound và một phương thức
Private là CalcTotal
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;
}
}
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection myConnection = new SqlConnection(''server=Localhost;database=pubs;uid =sa;pwd'');
SqlCommand myCommand = new SqlCommand(''SELECT title, price FROM Titles WHERE price > 0'', myConnection);
try
{
myConnection.Open();
MyGrid.DataSource = myCommand.ExecuteReader();
MyGrid.DataBind();
myConnection.Close();
}
catch(Exception ex)
{
HttpContext.Current.Response.Write(ex.ToString());
}
}
private void CalcTotal(string _price)
{
try
{
runningTotal += Double.Parse(_price);
}
catch
{
}
}
Sự kiện MyGrid_ItemDataBound
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);
}
}
Theo diễn đàn tin học
Nguồn:
________________
Tham khảo blog về lập trình :
Kiến thức về
Kiến thức về
Tham gia các khóa học tại