一个用泛型,和Sql语句分页的源代码

   
protected void Page_Load(object sender, EventArgs e)
    {
        
if (!Page.IsPostBack)
            BindDataGridView();
    }

    
private void BindDataGridView() 
    {
        
this.ProductGridView.DataSource = CreateDataSource();
        
this.ProductGridView.DataBind();
    }

    
private IList<ProductInfo> CreateDataSource()
    {
        
int totalRecords = 0;
        IList
<ProductInfo> products = GetProducts(Pager1.CurrentPageIndex, Pager1.PageSize, out  totalRecords);
        
this.Pager1.TotalRecords = totalRecords;
        
return products;
    }

    
private IList<ProductInfo> GetProducts(int pageIndex,int pageSize,out int totalRecords)
    {
        
string conenctionString = "Data Source=.;Initial Catalog=Northwind;Integrated Security=True";
        StringBuilder sb 
=new StringBuilder();
        sb.Append(
" DECLARE @PageLowerBound int  DECLARE @PageUpperBound int ");
        sb.Append(
" SET @PageLowerBound = @PageSize * @PageIndex  SET @PageUpperBound = @PageLowerBound + @PageSize - 1 ");
        sb.Append(
" CREATE TABLE #PageIndex(Id   int  IDENTITY(0,1) NOT NULL, ProductID int) ");
        sb.Append(
" INSERT #PageIndex(ProductID) " + 
                  
" SELECT ProductID "+
                  
" FROM Products " +
                  
" ORDER BY ProductID " );
        sb.Append(
" SELECT @TotalRecords = @@ROWCOUNT ");
        sb.Append(
" SELECT pt.CategoryID, pt.ProductID,pt.ProductName "+
                  
" FROM #PageIndex p,Products pt "+
                  
" WHERE p.ProductID =pt.ProductID AND "+
                  
" p.Id >= @PageLowerBound AND p.Id <= @PageUpperBound "+
                  
" ORDER BY pt.ProductID ");
        List
<ProductInfo> products = new List<ProductInfo>();
        
using (SqlConnection cnn = new SqlConnection(conenctionString))
        {
            SqlCommand cmd 
= new SqlCommand(sb.ToString(), cnn);
            cmd.CommandType 
= CommandType.Text;

            cmd.Parameters.Add(
new SqlParameter("@PageIndex", SqlDbType.Int));
            cmd.Parameters[
"@PageIndex"].Value = pageIndex;
            cmd.Parameters.Add(
new SqlParameter("@PageSize", SqlDbType.Int));
            cmd.Parameters[
"@PageSize"].Value = pageSize;
            cmd.Parameters.Add(
new SqlParameter("@TotalRecords", SqlDbType.Int));
            cmd.Parameters[
"@TotalRecords"].Direction = ParameterDirection.Output;
            cnn.Open();
            
using (SqlDataReader dr = cmd.ExecuteReader())
            {
                
while (dr.Read())
                    products.Add(
new ProductInfo(dr.GetInt32(0), dr.GetInt32(1), dr.GetString(2)));
            }
            totalRecords 
= (int)cmd.Parameters["@TotalRecords"].Value;
        }
        
return products;
    }
posted @ 2007-09-17 15:27  兴百放  阅读(389)  评论(0编辑  收藏  举报