1. 程式人生 > >GridView增加一個統計行的方法

GridView增加一個統計行的方法

 CMB專案中要涉及到stock的統計功能,由於是採用了gridview來實現資料的顯示,這裡就碰到了一個問題,在需求分析裡客戶要求對所有的股票進行一個統計,如下圖:

按此在新視窗開啟圖片

大家看在最下面的一行,只出現了一個數值,其它列都不存在數值,而這個數的功能主要是對上面這行"持倉股票市值進行一個總的統計",這是如何實現的呢?

首先,我們要把gridview裡面的屬性中ShowFooter="True",就是把gridview的頁尾開啟,這只是第一步。
第二步:在雙擊屬性面板中的事件,讓他自動生成一個GridView1_RowDataBound的事件,我們最終就是要在裡面寫幾行簡單的程式碼實現功能了.
第三步:在protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)加入程式碼了,由於我這裡是做需求分析時,只要在頁面裡顯示出效果就可以了,所以我的程式碼比較簡單。但是如果你要加上統計功能的話,你就可以在裡面自定義一些相關變數,或呼叫相關的方法就可以了,我這裡只是一個框架了.

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
     {
        
         decimal totalstock=0;

         if (e.Row.RowType == DataControlRowType.DataRow)
         {
            // totalstock += Convert.ToDecimal(DataBinder.Eval(e.Row.DataItem, "stockholdmarketprice"));

             // totalstock += DataBinder.Eval(e.Row.DataItem, "stockholdmarketprice");

            //在這裡就可以實現總和的計算了

         }
         else if(e.Row.RowType == DataControlRowType.Footer)
         {
             e.Row.Cells[3].Text="持倉總市值";
             e.Row.Cells[3].HorizontalAlign = HorizontalAlign.Right;
             e.Row.Cells[4].Text = "HKD15,000,000";

         }

這裡如果不使用這個事件的話,只在設計的aspx頁面中設定<FooterTemplate>來實現的話,就會發現所得到的效果是在每行資料中都會多出一個空白列,如圖:
按此在新視窗開啟圖片




在vs2005中提供的MSDN對GridView.RowDataBound 事件 的描述是這樣的:

呈現 GridView 控制元件之前,該控制元件中的每一行必須繫結到資料來源中的一條記錄。將某個資料行(用 GridViewRow 物件表示)繫結到 GridView 控制元件中的資料以後,將引發 RowDataBound 事件。這使您可以提供一個這樣的事件處理方法,即每次發生此事件時都執行一個自定義例程(如修改繫結到該行的資料的值)。

它也提供了一個example出來


程式程式碼:
<%@ Page language="C#"%>

<script runat="server">


  
void CustomersGridView_RowDataBound(Object sender, GridViewRowEventArgs e)
  
...{
        
    
if(e.Row.RowType == DataControlRowType.DataRow)
    
...{
      
// Display the company name in italics.
       e.Row.Cells[1].Text ="<i>"+ e.Row.Cells[1].Text +"</i>";
        
     }

    
   }


</script>


<html>
  
<body>
    
<form runat="server">
        
      
<h3>GridView RowDataBound Example</h3>

      
<asp:gridview id="CustomersGridView"
         datasourceid
="CustomersSqlDataSource"
         autogeneratecolumns
="true"
         allowpaging
="true"
         onrowdatabound
="CustomersGridView_RowDataBound"
         runat
="server">
      
</asp:gridview>
            
      
<!-- This example uses Microsoft SQL Server and connects  -->
      
<!-- to the Northwind sample database. Use an ASP.NET     -->
      
<!-- expression to retrieve the connection string value   -->
      
<!-- from the Web.config file.                            -->
      
<asp:sqldatasource id="CustomersSqlDataSource"  
         selectcommand
="Select [CustomerID], [CompanyName], [Address], [City], [PostalCode], [Country] From [Customers]"
         connectionstring
="<%$ ConnectionStrings:NorthWindConnectionString%>"
         runat
="server">
      
</asp:sqldatasource>
            
            
    
</form>
  
</body>
</html>