ASP.NET 2.0 GridView 範例集

来源:互联网 发布:淘宝退款理由做工瑕疵 编辑:程序博客网 时间:2024/04/28 05:33
ASP.NET 2.0 GridView 範例集
 
文/黃忠成
 
這篇文章從何來?
 
   在寫ASP.NET AJAX/Silverlight書之前,我曾經動過念頭撰寫一本ASP.NET 2.0聖經類型的書籍,也付諸執行了一段時間,完成了近500頁的書稿(500頁,僅是此書的3章....,全書規劃有15章),但由於工作上的關係,我終究沒能在ASP.NET 3.5推出前完成這一本書,只是將書中的ASP.NET/Silverlight抽出成為另一本書,但東西寫都寫好了,不將其公諸於世,總覺得對不起她們(我一直認為,文章在其完成時,即擁有作者所賦與的生命),雖然我可以將其收錄在未來可能撰寫的ASP.NET 3.5新書中,但由於近一年內的新書計劃中並沒有排定此書,遂決定將其中較實用的技巧抽出,貼在BLOG上面,與各位讀者分享,也算是送給各位長期支持我的讀者們,一份意外的聖誕禮物吧 ^_^。
 
PS:文章未經潤飾,不通順之處還請見諒。
 
 
漸層光棒
 
 不喜歡GridView控件單調的Header區、單調的選取光棒嗎?這裡有個小技巧可以讓你的GridView控件看起來與眾不同,請先準備兩張圖形。
圖4-8-50(4-71.tif)
這種漸層圖形可以用Photoshop或PhotoImpact輕易做出來,接著將這兩個圖形檔加到專案的Images目錄中,左邊取名為titlebar.gif、右邊取名為gridselback.gif,然後開啟一個新網頁,組態SqlDataSource控件連結到任一資料表,再加入GridView控件繫結至此SqlDataSource控件,接著將Enable Selection打勾,切換至網頁Source頁面,加入CSS的程式碼。
程式4-8-10
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="GrandientSelGrid.aspx.cs" Inherits="GrandientSelGrid" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<style type="text/css">
.grid_sel_back
{
 background-image:url(Images/gridselback.gif);
 background-repeat:repeat-x
}
.title_bar
{
           background-image:url(Images/titlebar.gif);
           background-repeat:repeat-x    
}
</style>
完成後切回設計頁面,設定GridView控件的SelectedRowStyle及HeaderStyle屬性。
圖4-8-51(4-72.tif)
完成後執行網頁,你會見到很不一樣的GridView。
圖4-8-52(4-73.tif)
 
2 Footer or 2 Header
 
 前面曾提及,GridView控件並沒有限制我們只能在裡面加入一個Footer,因此我們可以透過程式4-8-11的方式,添加另一個Footer至GridView控件中。
程式4-8-11
protected void GridView1_PreRender(object sender, EventArgs e)
{
     //if no-data in datasource,GridView will not create ChildTable.
     if (GridView1.Controls.Count > 0 && GridView1.Controls[0].Controls.Count > 1)
     {
          GridViewRow row2 = new GridViewRow(-1, -1,
DataControlRowType.Footer, DataControlRowState.Normal);
          TableCell cell = new TableCell();
          cell.Text = "Footer 2";
         cell.Attributes["colspan"] = GridView1.Columns.Count.ToString(); //merge columns
          row2.Controls.Add(cell);
         GridView1.Controls[0].Controls.AddAt(GridView1.Controls[0].Controls.Count - 1, row2);
      }
}
相同的,同樣的方法也可以用於添加另一個Header至GridView控件中,這個範例看起來無用,但是卻給了無限的想像空間,這是實現GridView Insert及Collapsed GridView功能的基礎。
 
Group Header
  
 想合併Header中的兩個欄位為一個嗎?很簡單!只要在RowCreated事件中將欲被合併的欄位移除,將另一欄位的colspan設為2即可。
程式4-8-12
protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
{
   if (e.Row.RowType == DataControlRowType.Header)
    {
       e.Row.Cells.RemoveAt(3);
       e.Row.Cells[2].Attributes["colspan"] = "2";
       e.Row.Cells[2].Text = "Contact Information";
    }
}
圖4-8-53為執行畫面。
圖4-8-53(4-74.tif)
我想,應該不需要我再解釋2這個數字從何而來了吧。 ^_^
 
Group Row
 想將同值的欄位合成一個嗎?4-8-13的程式碼可以幫你達成。
程式4-8-13
private void PrepareGroup()
{
      int lastSupID = -1;
      GridViewRow currentRow = null;
      List<GridViewRow> tempModifyRows = new List<GridViewRow>();
      foreach (GridViewRow row in GridView1.Rows)
      {           
         if (row.RowType == DataControlRowType.DataRow)
         {
            if (currentRow == null)
            {
                currentRow = row;
                int.TryParse(row.Cells[2].Text, out lastSupID);
                continue;
            }
 
            int currSupID = -1;
            if (int.TryParse(row.Cells[2].Text, out currSupID))
            {
               if (lastSupID != currSupID)
               {
                  currentRow.Cells[2].Attributes["rowspan"] = (tempModifyRows.Count+1).ToString();
                  currentRow.Cells[2].Attributes["valign"] = "center";                       
                  foreach (GridViewRow row2 in tempModifyRows)
                     row2.Cells.RemoveAt(2);
                  lastSupID = currSupID;
                  tempModifyRows.Clear();
                  currentRow = row;
                  lastSupID = currSupID;
               }
               else
                  tempModifyRows.Add(row);
        }                   
   }
 }
 
 if (tempModifyRows.Count > 0)
 {
       currentRow.Cells[2].Attributes["rowspan"] = (tempModifyRows.Count + 1).ToString();
       currentRow.Cells[2].Attributes["valign"] = "center";
       foreach (GridViewRow row2 in tempModifyRows)
            row2.Cells.RemoveAt(2);
 }
}
 
protected void GridView1_PreRender(object sender, EventArgs e)
{
    PrepareGroup();
}
這段程式碼應用了先前所提過的GridViewRow控件及TableCell的使用方式,圖4-8-54為執行結果。
圖4-8-54
 
 
Master-Detail GridView
 
 Master-Detail,也就是主明細表的顯示,是資料庫應用常見的功能,運用DataSource及GridView控件可以輕易做到這點,請建立一個網頁,加入兩個GridView控件,一名為GridView1,用於顯示主表,二名為GridView2,用於顯示明細表,接著加入兩個SqlDataSource控件,一個連結至Northwind資料庫的Orders資料表,另一個連結至Order Details資料表,於連結至Order Details資料表的SqlDataSource中添加WHERE條件來比對OrderID欄位,值來源設成GridView1的SelectedValue屬性。
圖4-8-61
接下來請將GridView1的DataSoruce設為Orders的SqlDataSource,GridView2的DataSource設為Order Details的SqlDataSource,最後將GridView1的Enable Selection打勾即可完成Master-Detail的範例。
圖4-8-62
那這是如何辦到的呢?當使用者點選GridView1上某筆資料的Select連結時,GridView1的SelectedValue屬性便會設成該筆資料的DataKeyName屬性所指定的欄位值,而連結至Order Details的SqlDataSource又以該屬性做為比對OrderID欄位時的值來源,結果便成了,使用者點選了Select連結,PostBack發生,GridView2向連結至Order Details的SqlDataSource索取資料,該SqlDataSource以GridView1.SelectedValue做為比對OrderID欄位的值,執行選取資料的SQL指令後,該結果集便是GridView1所選取那筆資料的明細了。
 
Master-Detail GridView Part 2
 
 前面的Master-Detail GridView控件應用,相信你已在市面上的書、或網路上見過,但此節中的GridView控件應用包你沒看過,但一定想過!請見圖4-8-63。
圖4-8-63
4-8-64
你一定很想驚呼?這是GridView嗎??不是第三方控件的效果吧?是的!這是GridView控件,而且只需要不到100行程式碼!!請先建立一個UserControlDetailsGrid.ascx,加入一個SqlDataSource控件連結至NorthwindOrder Details資料表,選取所有欄位,接著在WHERE區設定如圖4-8-65的條件。
4-8-65
接著加入一個GridView控件繫結至此SqlDataSource控件,並將Enable Editing打勾,然後於原始碼中鍵入4-8-17的程式碼。
程式4-8-17
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
 
public partial class DetailsGrid : System.Web.UI.UserControl
{
    public int OrderID
    {
        get
        {
            object o = ViewState["OrderID"];
            return o == null ? -1 : (int)o;
        }
        set
        {
            ViewState["OrderID"] = value;
            SqlDataSource1.SelectParameters[0].DefaultValue = value.ToString();
        }
    }
    protected void Page_Load(object sender, EventArgs e)
    {
    }
}
 
接著建立一個新網頁,加入SqlDataSource控件繫結至NorthwindOrders資料表,然後加入一個GridView控件,並於其欄位編輯器中加入一個TemplateField,於其內加入一個LinkButton控件,設定其屬性如圖4-8-66
4-8-66
然後設定LinkButtonDataBindings如圖4-8-67
4-8-67
然後於原始碼中鍵入4-8-18的程式碼。
程式4-8-18
using System;
using System.Collections.Generic;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
 
public partial class CollapseGridView : System.Web.UI.Page
{
    private List<int> _collaspedRows = new List<int>();
    private List<GridViewRow> _delayAddRows = new List<GridViewRow>();
 
    private bool RowIsCollasped(GridViewRow row)
    {
        if(_collaspedRows.Count > 0)
            return _collaspedRows.Contains((int)GridView1.DataKeys[row.RowIndex].Value);
        return false;
    }
 
    private void CreateDetailRow(GridViewRow gridRow)
    {
        if (RowIsCollasped(gridRow))
        {
            GridViewRow row = new GridViewRow(gridRow.RowIndex, -1,
DataControlRowType.DataRow, DataControlRowState.Normal);
            TableCell cell = new TableCell();
            row.Cells.Add(cell);
            TableCell cell2 = new TableCell();
            cell2.Attributes["colspan"] = (GridView1.Columns.Count - 1).ToString();
            Control c = LoadControl("DetailsGrid.ascx");
            ((DetailsGrid)c).OrderID = (int)GridView1.DataKeys[gridRow.RowIndex].Value;
            cell2.Controls.Add(c);
            row.Cells.Add(cell2);
            _delayAddRows.Add(row);
        }
    }
 
    protected void Page_Load(object sender, EventArgs e)
    {
 
    }  
 
    protected override void LoadViewState(object savedState)
    {
        Pair state = (Pair)savedState;
        base.LoadViewState(state.First);
        _collaspedRows = (List<int>)state.Second;
    }
 
    protected override object SaveViewState()
    {
        Pair state = new Pair(base.SaveViewState(), _collaspedRows);
        return state;
    }
}
接下來在TemplateField中的LinkButtonClick事件中鍵入4-8-19的程式碼。
程式4-8-19
protected void LinkButton1_Click(object sender, EventArgs e)
{
        LinkButton btn = (LinkButton)sender;       
        int key = int.Parse(btn.CommandArgument);
        if (_collaspedRows.Contains(key))
        {
            _collaspedRows.Remove(key);
            GridView1.DataBind();
        }
        else
        {
            _collaspedRows.Clear(); // clear.
            _collaspedRows.Add(key);
            GridView1.DataBind();
        }
}
最後在GridView控件的RowCreatedPageIndexChanging事件中鍵入4-8-20的程式碼。
程式4-8-20
protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
{
        if(e.Row.RowType == DataControlRowType.DataRow)
            CreateDetailRow(e.Row);
        else if (e.Row.RowType == DataControlRowType.Pager && _delayAddRows.Count > 0)
        {
            for (int i = 0; i < GridView1.Rows.Count; i++)
            {
                if (RowIsCollasped(GridView1.Rows[i]))
                {
                    GridView1.Controls[0].Controls.AddAt(GridView1.Rows[i].RowIndex + 2,
_delayAddRows[0]);
                    _delayAddRows.RemoveAt(0);
                }
            }
        }
    }
 
    protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        _collaspedRows.Clear();
    }
執行後你就能看到前圖的效果了,那具體是如何做到的呢?從前面的說明,我們知道了可以在GridView控件中動態的插入一個 GridViewRow控件,而GridViewRow控件可以擁有多個Cell,每個Cell可以擁有子控件,那麼當這個子控件是一個UserControl ?相信說到這份上,讀者已經知道整個程式的運行基礎及概念了,剩下的細節如LoadViewStateSaveViewState皆已在前面章節提過,看懂這個範例後!你應該也想到了其它的應用了(UserControl中放DetailsViewFormViewMultiView,哈!),對於GridView!你已經毫無疑問了!
 
 
4-8-4、GridView的效能
 
 OK,GridView控件功能很強大,但是如果你仔細思考下GridView控件的分頁是如何做的,會發現她的做法其實隱含著一個很大的效能問題,GridView控件在分頁功能啟動的情況下,會建立一個PageDataSource物件,由這個物件負責向DataSource索取資料,於索取資料時一併傳入DataSourceSelectArgument物件,此物件中便包含了起始的列及需要的列數,看起來似乎沒啥問題嗎?其實不然,當DataSource控件不支援分頁時,PageDataSource物件只能以該DataSource所傳回的資料來做分頁,簡略的說!SqlDataSource控件是不支援分頁的,這時PageDataSource會要求SqlDataSource控件傳回資料,而SqlDataSource控件就用SelectQuery中的SQL指令向資料庫要求資料,結果便是,當該SQL指令選取100000筆資料時,SqlDataSource所傳回給PageDataSource的資料也是100000筆!!這意味著,GridView每次做資料繫結顯示時,是用100000筆資料在分頁,不管顯示的是幾筆,存在於記憶體中的都是100000筆!如果同時有10個人、100個人在使用此網頁,可想而知Server的負擔有多重了,即使有Cache加持,一樣會有100000筆資料在記憶體中!以往在ASP.NET 1.1時,可以運用DataGrid控件的CustomPaging功能來解決此問題,但GridView控件並未提供這個功能,我們該怎麼處理這個問題呢?在提出解決方案前,我們先談談GridView控件為何將這麼有用的功能移除了?答案很簡單,這個功能已經被移往DataSource控件了,這是因為DataSource控件所需服務的不只是GridView,FormView、DetailsView都需要她,而且她們都支援分頁,如果將CustomPaging直接做在這些控件上,除了控件必須有著重複的程式碼外,設計師於撰寫分頁程式時,也需針對不同的控件來處理,將這些移往DataSource控件後,便只會有一份程式碼。說來好聽,那明擺著SqlDataSource控件就不支援分頁了,那該如何解決這個問題了,答案是ObjectDataSource,這是一個支援分頁的DataSource控件,只要設定幾個屬性及對資料提供者做適當的修改後,便可以達到手動分頁的效果了。請建立一個WebiSte專案,添加一個DataSet連結到Northwind的Customers資料表,接著新增一個Class,檔名為NorthwindCustomersTableAdapter.cs,鍵入4-8-26的程式碼。
程式4-8-26
using System;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
 
namespace NorthwindTableAdapters
{
    public partial class CustomersTableAdapter
    {
        [System.ComponentModel.DataObjectMethodAttribute(
System.ComponentModel.DataObjectMethodType.Select, true)]
        public virtual Northwind.CustomersDataTable GetData(int startRowIndex, int maximumRows)
        {
            this.Adapter.SelectCommand =
 new System.Data.SqlClient.SqlCommand("SELECT {COLUMNS} FROM " +
 "(SELECT {COLUMNS},ROW_NUMBER() OVER(ORDER BY {SORT}) As RowNumber FROM {TABLE} {WHERE}) {TABLE} " +                                                           "WHERE RowNumber > {START} AND RowNumber < {FETCH_SIZE}",Connection);
            this.Adapter.SelectCommand.CommandText = this.Adapter.SelectCommand.CommandText.Replace("{COLUMNS}", "*");
            this.Adapter.SelectCommand.CommandText = this.Adapter.SelectCommand.CommandText.Replace("{TABLE}", "Customers");
            this.Adapter.SelectCommand.CommandText = this.Adapter.SelectCommand.CommandText.Replace("{SORT}", "CustomerID");
            this.Adapter.SelectCommand.CommandText = this.Adapter.SelectCommand.CommandText.Replace("{WHERE}", "");
            this.Adapter.SelectCommand.CommandText = this.Adapter.SelectCommand.CommandText.Replace("{START}", startRowIndex.ToString());
            this.Adapter.SelectCommand.CommandText = this.Adapter.SelectCommand.CommandText.Replace("{FETCH_SIZE}", (startRowIndex+maximumRows).ToString());
            Northwind.CustomersDataTable dataTable = new Northwind.CustomersDataTable();
            this.Adapter.Fill(dataTable);
            return dataTable;
        }
 
        public virtual int GetCount(int startRowIndex, int maximumRows)
        {
            SqlCommand cmd = new System.Data.SqlClient.SqlCommand("SELECT COUNT(*) AS TOTAL_COUNT FROM Customers", Connection);           
            Connection.Open();
            try
            {
                return (int)cmd.ExecuteScalar();
            }
            finally
            {
                Connection.Close();
            }
        }
    }
}
此程式提供了兩個函式,GetData函式需要兩個參數,一個是起始的筆數,一個是選取的筆數,利用這兩個參數加上SQL Server 2005新增的RowNumber,便可以向資料庫要求傳回特定範圍的資料。那這兩個參數從何傳入的呢?當GridView向ObjectDataSource索取資料時,便會傳入這兩個參數,例如當GridView的PageSize是10時,第1頁時傳入的startRowIndex便是10,maximumRows就是10,以此類推。第二個函式是GetCount,對於GridView來說,她必須知道繫結資料的總頁數才能顯示Pager區,而此總頁數必須由資料總筆數算出,此時GridView會向PageDataSource要求資料的總筆數,而PageDataSource在DataSource控件支援分頁的情況下,會要求其提供總筆數,這時此函式就會被呼叫了。大致了解這個程式後,回到設計頁面,加入一個ObjectDataSource控件,於SELECT頁次選取帶startRowIndex及maximumRows參數的函式。
圖4-8-68
按下Next按紐後,精靈會要求我們設定參數值來源,請直接按下Finish來完成組態。
圖4-8-69
接著設定ObjectDataSource的EnablePaging屬性為True,SelectCountMethod屬性為GetCount(對應了程式4-8-26中的GetCount函式),最後放入一個GridView控件,繫結至此ObjectDataSource後將Enable Paging打勾,就完成了手動分頁的GridView範例了。
圖4-8-70
在效能比上,手動分頁的效能在資料量少時絕對比Cache來的慢,但資料量大時,手動分頁的效能及記憶體耗費就一定比Cache來的好。
 
 

Trackback: http://tb.blog.csdn.net/TrackBack.aspx?PostId=1958167

 
原创粉丝点击