1. 程式人生 > >關於GridView和ObjectDataSource結合的分頁問題

關於GridView和ObjectDataSource結合的分頁問題

用了我一天的時間,才把這個問題搞明白,其中還參考了許多網友的示例,唉,失敗呀~!

先貼一下原始碼~!

頁面的:

<asp:ObjectDataSource ID="ObjectDataSource1" runat="server" SelectMethod="GetUsers"
            TypeName="DAL.DataManager" EnablePaging="True" MaximumRowsParameterName="maxRows" SelectCountMethod="GetUsersCount" StartRowIndexParameterName="RowIndex">
           <!--注意此處要把引數資訊刪除-->
        </asp:ObjectDataSource>
        
        <asp:GridView ID="GridView1" runat="server" AllowPaging="True" AutoGenerateColumns="False"
            DataSourceID="ObjectDataSource1">
            <Columns>
                <asp:BoundField DataField="UserName" HeaderText="UserName" SortExpression="UserName" />
                <asp:BoundField DataField="UserID" HeaderText="UserID" SortExpression="UserID" />
                <asp:BoundField DataField="Description" HeaderText="Description" SortExpression="Description" />
            </Columns>
        </asp:GridView>

後臺程式碼:

UserInfo類:

using System;
using System.Collections.Generic;
using System.Text;

namespace DAL
{
   public  class UserInfo
    {
       private int _userid;
       private string _username;
       private string _description;

       public UserInfo()
       { }

       public UserInfo( int userid , string username , string desc )
       {
           _userid = userid;
           _username = username;
           _description = desc;
       }

       public int UserID
       {
           get
           {
               return _userid;
           }
           set
           {
               _userid = value;
           }
       }

       public string UserName
       {
           get { return _username; }
           set { _username = value; }
       }
       public string Description
       {
           get { return _description; }
           set { _description = value; }
       }
    }
}

DataManager類:

using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.SqlClient;
namespace DAL
{
  
/// <summary>
/// DataManager 的摘要說明
/// </summary>
    public class DataManager
    {
        private SqlConnection con = null; //連線物件
        private SqlCommand cmd = null;  //command執行物件
        private SqlDataAdapter da = null; //介面卡物件

        /**/
        /// <summary>
        /// DAL物件構造
        /// </summary>
        public DataManager()
        {
            //
            // TODO: Add constructor logic here
            //
        }

        /**/
        /// <summary>
        /// 開啟資料庫連線
        /// </summary>
        private void OpenConnection()
        {
            try
            {
                string conString = "server=。;uid=sa;pwd=sa;database=account"; //換成你的資料庫
                con = new SqlConnection( conString );
                if ( ConnectionState.Closed == con.State )
                {
                    con.Open();
                }
            }
            catch ( SqlException ex )
            {
                throw new Exception( "資料庫無法訪問" , ex );
            }
        }

        /**/
        /// <summary>
        /// 關閉資料庫連線
        /// </summary>
        private void CloseConnection()
        {
            if ( ConnectionState.Open == con.State )
            {
                try
                {
                    con.Close();
                }
                catch ( SqlException ex )
                {
                    throw new Exception( "資料庫無法關閉" , ex );
                }
            }
        }

        /**/
        /// <summary>
        /// 取得使用者列表
        /// </summary>
        /// <param name="rowIndex">行索引</param>
        /// <param name="recordCount">頁顯示量(增量)</param>
        /// <returns>使用者列表資料集</returns>
        public IList<UserInfo> GetUsers( int RowIndex , int maxRows )
        {
            OpenConnection();
            IList<UserInfo> user = new List<UserInfo>();
            try
            {
                cmd = new SqlCommand();
                cmd.Connection = con;
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.CommandText = "GetUsers";

                SqlParameter spRowIndex = new SqlParameter( "@pageindex" , SqlDbType.Int , 4 );
                spRowIndex.Direction = ParameterDirection.Input;
                SqlParameter spRecordCount = new SqlParameter( "@pagesize" , SqlDbType.Int , 4 );
                spRecordCount.Direction = ParameterDirection.Input;
                SqlParameter spDocount = new SqlParameter( "@docount" , SqlDbType.Bit );
                spDocount.Direction = ParameterDirection.Input;

                cmd.Parameters.Add( spRowIndex );
                cmd.Parameters.Add( spRecordCount );
                cmd.Parameters.Add( spDocount );

                spRowIndex.Value = RowIndex/maxRows ;    //注意此處GridView傳入的不是頁碼,而是第多少記錄,比如第二頁的話,他會傳入10,第三頁傳入20,以此...
                spRecordCount.Value = maxRows;
                spDocount.Value = false;

                SqlDataReader dr = cmd.ExecuteReader();

                while ( dr.Read() )
                {
                    UserInfo userinfo = new UserInfo( dr.GetInt32( 0 ) , dr.GetString( 1 ) , dr.GetString( 2 ) );

                    user.Add( userinfo );
                }

                return user;
            }
            catch ( SqlException ex )
            {
                throw new Exception( "無法取得有效資料" , ex );
            }
            finally
            {
                CloseConnection();
            }
        }

        /**/
        /// <summary>
        /// 取得使用者總數
        /// </summary>
        /// <returns>使用者總數</returns>
        public int GetUsersCount( )
        {
            OpenConnection();
            try
            {
                cmd = new SqlCommand();
                cmd.Connection = con;
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.CommandText = "GetUsers";

                SqlParameter spRowIndex = new SqlParameter( "@pageindex" , SqlDbType.Int , 4 );
                spRowIndex.Direction = ParameterDirection.Input;
                SqlParameter spRecordCount = new SqlParameter( "@pagesize" , SqlDbType.Int , 4 );
                spRecordCount.Direction = ParameterDirection.Input;
                SqlParameter spDocount = new SqlParameter( "@docount" , SqlDbType.Bit );
                spDocount.Direction = ParameterDirection.Input;

                cmd.Parameters.Add( spRowIndex );
                cmd.Parameters.Add( spRecordCount );
                cmd.Parameters.Add( spDocount );

                spRowIndex.Value = 1;
                spRecordCount.Value = 10;
                spDocount.Value = true;

                da = new SqlDataAdapter( cmd );

                int count = Convert.ToInt32( cmd.ExecuteScalar().ToString() );
                return count;
            }
            catch ( SqlException ex )
            {
                throw new Exception( "無法取得有效資料" , ex );
            }
            finally
            {
                CloseConnection();
            }
        }
    }
}

儲存過程:

CREATE procedure GetUsers
(@pagesize int,
@pageindex int,
@docount bit)
as
set nocount on
if(@docount=1)
select count(UserID) from MyUsers
else
begin
declare @PageLowerBound int
declare @PageUpperBound int
set @PageLowerBound=(@pageindex)*@pagesize
set @PageUpperBound=@PageLowerBound+@pagesize
create table #pageindex(id int identity(1,1) not null,nid int)
set rowcount @PageUpperBound
insert into #pageindex(nid)
select UserID from MyUsers order by UserID desc
select O.*
from MyUsers O,#pageindex p
where O.UserID=p.nid and p.id>@PageLowerBound and p.id<=@PageUpperBound order by p.id
end
set nocount off
GO

好了,表結構不用貼了吧,相信大家已經清楚了。有啥問題可以和我聯絡:[email protected]