技术开发 频道

ASP.NET中为DataGrid添加合计字段

  Page_Load 事件

  在 Page_Load 事件中,你所要做的就是连接到 SQL Server 并执行一个简单的 SqlCommand。 你取得了所有 Price 值>0 的 title 和 price 数据。你使用 SqlCommand.ExecuteReader 方法返回一个 SqlDataReader 并将其直接绑定到 DataGrid (MyGrid)。

protected void Page_Load(object sender, EventArgs e) {  SqlConnection myConnection = new SqlConnection
(
"server=Localhost;database=pubs;uid=sa;pwd=;");
//创建SQL连接  SqlCommand myCommand = new SqlCommand
(
"SELECT title, price FROM Titles WHERE price > 0", myConnection);
//创建SQL命令  try  {   myConnection.Open();//打开数据库连接   MyGrid.DataSource = myCommand.ExecuteReader();
//指定 DataGrid 的数据源   MyGrid.DataBind();//绑定数据到 DataGrid   myConnection.Close();//关闭数据连接  }  catch(Exception ex)  {   //捕获错误   HttpContext.Current.Response.Write(ex.ToString());  } }
  CalcTotals 方法
 
  CalcTotals 方法用来处理 runningTotal 变量。这个值将以字符串形式来传递。 你需要将它解析为双精度型,然后 runningTotal 变量就成了双精度类型。
private void CalcTotal(string _price) {  try  {   runningTotal += Double.Parse(_price);  }  catch  {   //捕获错误  } }
   MyGrid_ItemDataBound 事件
 
  MyGrid_ItemDataBound 事件在数据源中每行绑定到 DataGrid 时被调用。在这个事件处理中,你可以处理每一行数据。这里你的目的是,你将需要调用 CalcTotals 方法并从 Price 列传递文本,并用金额型格式化每一行的 Price 列, 并在页脚行中显示 runningTotal 的值。
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);  } }
  
     在 MyGrid_ItemDataBound 事件句柄中,首先你得使用 ListItemType 判断当前的 DataGridItem 是一个数据项还是AlternatingItem 行。如果是数据项,你调用 CalcTotals,并将 Price 列的值作为参数传递给它;然后你以金额格式对 Price 列进行格式化及着色。
 
  如果 DataGridItem 是页脚,可以用金额格式显示 runningTotal。
 
       总结
 
  在这份指南中,你学到了怎样使用 DataGrid.OnItemDataBound 事件来实现运行时对DataGrid 的某一列进行统计。使用这个事件,你可以创建一个列的合计并可对DataGrid行的页脚进行着色。

 

0
相关文章