asp.net中分頁控制元件AspNetPager美化樣式

暖楓無敵發表於2014-12-30

在asp.net開發中資料列表分頁是再常見不過的功能了,相信大家使用AspNetPager的也很多,使用CSS可以讓樣式更好看,如下圖:


新建一個名為content.css檔案,如下:

/*分頁控制元件*/
.paginator
{
    font: 11px Arial, Helvetica, sans-serif;
    padding: 0px 5px 0px 15px;
    margin: 0px;
    font-family:微軟雅黑;
    font-size:13px;
}

/* 頁面的背景以及字型*/
.paginator a
{
    padding: 1px 6px;
    border: solid 1px #7EC0EE;
    background:url(../Images/System/pages.png);
    text-decoration: none;
    margin-right: 2px;
    color:#436EEE;
}

.paginator a:visited
{
    padding: 1px 6px;
    border: solid 1px #99d6ff;
    background: #fff;
    text-decoration: none;
    color:#4cb8ff; 
}

.paginator .cpb
{
    padding: 1px 6px;
    font-weight: bold;
    font-size: 13px;
    border: none;
}

.paginator a:hover
{
    color:#EE4000;
    background: #ebf7ff;
    border-color: #99d6ff;
    text-decoration: none;
}

.paginator span
{
    color: #4cb8ff;
}


web系統中新增AspNetPager.dll引用,然後頭部新增如下內容:

<%@ Register Assembly="AspNetPager" Namespace="Wuqi.Webdiyer" TagPrefix="webdiyer" %>


引入css,如下:

<link href="../css/content.css" rel="stylesheet" type="text/css" />


 <webdiyer:AspNetPager ID="AspNetPager" runat="server" Width="90%" UrlPaging="true"
            ShowPageIndexBox="Always" AlwaysShow="True" PageIndexBoxType="DropDownList" TextBeforePageIndexBox="轉到: "
            HorizontalAlign="Right" OnPageChanged="AspNetPager_PageChanged" EnableTheming="true"
            FirstPageText="首頁" LastPageText="尾頁" CssClass="paginator" NextPageText="下一頁" PrevPageText="上一頁">
 </webdiyer:AspNetPager>


    private int pageSize = int.Parse(CommonClass.GetContentFromWebConfig("PageSize"));
    int totalCount = 0;
    int totalPageCount = 0;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindStateDropDownList();
            this.AspNetPager.PageSize = pageSize;
            BindGrid("");
            GetTotal();
        }
    }

    protected void btnQuery_Click(object sender, EventArgs e)
    {
        AspNetPager.CurrentPageIndex = 1;
        string where = getQueryString();
        BindGrid(where);
        GetTotal();
    }


    private void GetTotal()
    {
        AspNetPager.RecordCount = totalCount;
    }

    private void BindGrid(string where)
    {
        int start = AspNetPager.StartRecordIndex;
        int end = AspNetPager.EndRecordIndex;
        string region = getAuthorityRegionList();
        string corporation = getAuthorityCorporationList();
        DataSet ds = SqlHelper.PageList(SqlHelper.LocalSqlServer, "T_Persons", "*", "PersonneId", " 1=1 and TypeId in(" + region + ") and BrandId in ("+corporation+") " + where + "", " TypeID desc", 1, 0, pageSize, AspNetPager.CurrentPageIndex, ref totalCount, ref totalPageCount);
        this.RptData.DataSource = ds;
        this.RptData.DataBind();
    }


通用分頁儲存過程程式碼如下:

 create PROC P_viewPage

    /**//*
        nzperfect [no_mIss] 高效通用分頁儲存過程(雙向檢索)
        敬告:適用於單一主鍵或存在唯一值列的表或檢視
        ps:Sql語句為8000位元組,呼叫時請注意傳入引數及sql總長度不要超過指定範圍
           
    */

    @TableName VARCHAR(200),     --表名
    @FieldList VARCHAR(2000),    --顯示列名,如果是全部欄位則為*
    @PrimaryKey VARCHAR(100),    --單一主鍵或唯一值鍵
    @Where VARCHAR(2000),        --查詢條件 不含'where'字元,如id>10 and len(userid)>9
    @Order VARCHAR(1000),        --排序 不含'order by'字元,如id asc,userid desc,必須指定asc或desc                                 
                                 --注意當@SortType=3時生效,記住一定要在最後加上主鍵,否則會讓你比較鬱悶
    @SortType INT,               --排序規則 1:正序asc 2:倒序desc 3:多列排序方法
    @RecorderCount INT,          --記錄總數 0:會返回總記錄
    @PageSize INT,               --每頁輸出的記錄數
    @PageIndex INT,              --當前頁數
    @TotalCount INT OUTPUT,      --記返回總記錄
    @TotalPageCount INT OUTPUT   --返回總頁數
AS
    SET NOCOUNT ON

    IF ISNULL(@TotalCount,'') = '' SET @TotalCount = 0
    SET @Order = RTRIM(LTRIM(@Order))
    SET @PrimaryKey = RTRIM(LTRIM(@PrimaryKey))
    SET @FieldList = REPLACE(RTRIM(LTRIM(@FieldList)),' ','')

    WHILE CHARINDEX(', ',@Order) > 0 OR CHARINDEX(' ,',@Order) > 0
    BEGIN
        SET @Order = REPLACE(@Order,', ',',')
        SET @Order = REPLACE(@Order,' ,',',')    
    END

    IF ISNULL(@TableName,'') = '' OR ISNULL(@FieldList,'') = '' 
        OR ISNULL(@PrimaryKey,'') = ''
        OR @SortType < 1 OR @SortType >3
        OR @RecorderCount  < 0 OR @PageSize < 0 OR @PageIndex < 0        
    BEGIN 
        PRINT('ERR_00')       
        RETURN
    END    

    IF @SortType = 3
    BEGIN
        IF (UPPER(RIGHT(@Order,4))!=' ASC' AND UPPER(RIGHT(@Order,5))!=' DESC')
        BEGIN PRINT('ERR_02') RETURN END
    END

    DECLARE @new_where1 VARCHAR(1000)
    DECLARE @new_where2 VARCHAR(1000)
    DECLARE @new_order1 VARCHAR(1000)   
    DECLARE @new_order2 VARCHAR(1000)
    DECLARE @new_order3 VARCHAR(1000)
    DECLARE @Sql VARCHAR(8000)
    DECLARE @SqlCount NVARCHAR(4000)

    IF ISNULL(@where,'') = ''
        BEGIN
            SET @new_where1 = ' '
            SET @new_where2 = ' WHERE  '
        END
    ELSE
        BEGIN
            SET @new_where1 = ' WHERE ' + @where 
            SET @new_where2 = ' WHERE ' + @where + ' AND '
        END

    IF ISNULL(@order,'') = '' OR @SortType = 1  OR @SortType = 2 
        BEGIN
            IF @SortType = 1 
            BEGIN 
                SET @new_order1 = ' ORDER BY ' + @PrimaryKey + ' ASC'
                SET @new_order2 = ' ORDER BY ' + @PrimaryKey + ' DESC'
            END
            IF @SortType = 2 
            BEGIN 
                SET @new_order1 = ' ORDER BY ' + @PrimaryKey + ' DESC'
                SET @new_order2 = ' ORDER BY ' + @PrimaryKey + ' ASC'
            END
        END
    ELSE
        BEGIN
            SET @new_order1 = ' ORDER BY ' + @Order
        END

    IF @SortType = 3 AND  CHARINDEX(','+@PrimaryKey+' ',','+@Order)>0
        BEGIN
            SET @new_order1 = ' ORDER BY ' + @Order
            SET @new_order2 = @Order + ','            
            SET @new_order2 = REPLACE(REPLACE(@new_order2,'ASC,','{ASC},'),'DESC,','{DESC},')            
            SET @new_order2 = REPLACE(REPLACE(@new_order2,'{ASC},','DESC,'),'{DESC},','ASC,')
            SET @new_order2 = ' ORDER BY ' + SUBSTRING(@new_order2,1,LEN(@new_order2)-1)            
            IF @FieldList <> '*'
                BEGIN            
                    SET @new_order3 = REPLACE(REPLACE(@Order + ',','ASC,',','),'DESC,',',')                              
                    SET @FieldList = ',' + @FieldList                    
                    WHILE CHARINDEX(',',@new_order3)>0
                    BEGIN
                        IF CHARINDEX(SUBSTRING(','+@new_order3,1,CHARINDEX(',',@new_order3)),','+@FieldList+',')>0
                        BEGIN 
                        SET @FieldList = 
                            @FieldList + ',' + SUBSTRING(@new_order3,1,CHARINDEX(',',@new_order3))                        
                        END
                        SET @new_order3 = 
                        SUBSTRING(@new_order3,CHARINDEX(',',@new_order3)+1,LEN(@new_order3))
                    END
                    SET @FieldList = SUBSTRING(@FieldList,2,LEN(@FieldList))                     
                END            
        END

    SET @SqlCount = 'SELECT @TotalCount=COUNT(*),@TotalPageCount=CEILING((COUNT(*)+0.0)/'
                    + CAST(@PageSize AS VARCHAR)+') FROM ' + @TableName + @new_where1
    
    IF @RecorderCount  = 0
        BEGIN
             EXEC SP_EXECUTESQL @SqlCount,N'@TotalCount INT OUTPUT,@TotalPageCount INT OUTPUT',
                               @TotalCount OUTPUT,@TotalPageCount OUTPUT
        END
    ELSE
        BEGIN
             SELECT @TotalCount = @RecorderCount            
        END

    IF @PageIndex > CEILING((@TotalCount+0.0)/@PageSize)
        BEGIN
            SET @PageIndex =  CEILING((@TotalCount+0.0)/@PageSize)
        END

    IF @PageIndex = 1 OR @PageIndex >= CEILING((@TotalCount+0.0)/@PageSize)
        BEGIN
            IF @PageIndex = 1 --返回第一頁資料
                BEGIN
                    SET @Sql = 'SELECT TOP ' + STR(@PageSize) + ' ' + @FieldList + ' FROM ' 
                               + @TableName + @new_where1 + @new_order1
                END
            IF @PageIndex >= CEILING((@TotalCount+0.0)/@PageSize)  --返回最後一頁資料
                BEGIN
                    SET @Sql = 'SELECT TOP ' + STR(@PageSize) + ' ' + @FieldList + ' FROM (' 
                               + 'SELECT TOP ' + STR(ABS(@PageSize*@PageIndex-@TotalCount-@PageSize)) 
                               + ' ' + @FieldList + ' FROM '
                               + @TableName + @new_where1 + @new_order2 + ' ) AS TMP '
                               + @new_order1                    
                END        
        END    
    ELSE
        BEGIN
            IF @SortType = 1  --僅主鍵正序排序
                BEGIN
                    IF @PageIndex <= CEILING((@TotalCount+0.0)/@PageSize)/2  --正向檢索
                        BEGIN
                            SET @Sql = 'SELECT TOP ' + STR(@PageSize) + ' ' + @FieldList + ' FROM ' 
                                       + @TableName + @new_where2 + @PrimaryKey + ' > '
                                       + '(SELECT MAX(' + @PrimaryKey + ') FROM (SELECT TOP '
                                       + STR(@PageSize*(@PageIndex-1)) + ' ' + @PrimaryKey 
                                       + ' FROM ' + @TableName
                                       + @new_where1 + @new_order1 +' ) AS TMP) '+ @new_order1
                        END
                    ELSE  --反向檢索
                        BEGIN
                            SET @Sql = 'SELECT TOP ' + STR(@PageSize) + ' ' + @FieldList + ' FROM (' 
                                       + 'SELECT TOP ' + STR(@PageSize) + ' ' 
                                       + @FieldList + ' FROM '
                                       + @TableName + @new_where2 + @PrimaryKey + ' < '
                                       + '(SELECT MIN(' + @PrimaryKey + ') FROM (SELECT TOP '
                                       + STR(@TotalCount-@PageSize*@PageIndex) + ' ' + @PrimaryKey 
                                       + ' FROM ' + @TableName
                                       + @new_where1 + @new_order2 +' ) AS TMP) '+ @new_order2 
                                       + ' ) AS TMP ' + @new_order1
                        END
                END
            IF @SortType = 2  --僅主鍵反序排序
                BEGIN
                    IF @PageIndex <= CEILING((@TotalCount+0.0)/@PageSize)/2  --正向檢索
                        BEGIN
                            SET @Sql = 'SELECT TOP ' + STR(@PageSize) + ' ' + @FieldList + ' FROM ' 
                                       + @TableName + @new_where2 + @PrimaryKey + ' < '
                                       + '(SELECT MIN(' + @PrimaryKey + ') FROM (SELECT TOP '
                                       + STR(@PageSize*(@PageIndex-1)) + ' ' + @PrimaryKey 
                                       +' FROM '+ @TableName
                                       + @new_where1 + @new_order1 + ') AS TMP) '+ @new_order1                               
                        END 
                    ELSE  --反向檢索
                        BEGIN
                            SET @Sql = 'SELECT TOP ' + STR(@PageSize) + ' ' + @FieldList + ' FROM (' 
                                       + 'SELECT TOP ' + STR(@PageSize) + ' ' 
                                       + @FieldList + ' FROM '
                                       + @TableName + @new_where2 + @PrimaryKey + ' > '
                                       + '(SELECT MAX(' + @PrimaryKey + ') FROM (SELECT TOP '
                                       + STR(@TotalCount-@PageSize*@PageIndex) + ' ' + @PrimaryKey 
                                       + ' FROM ' + @TableName
                                       + @new_where1 + @new_order2 +' ) AS TMP) '+ @new_order2 
                                       + ' ) AS TMP ' + @new_order1
                        END  
                END                         
            IF @SortType = 3  --多列排序,必須包含主鍵,且放置最後,否則不處理
                BEGIN
                    IF CHARINDEX(',' + @PrimaryKey + ' ',',' + @Order) = 0 
                    BEGIN PRINT('ERR_02') RETURN END
                    IF @PageIndex <= CEILING((@TotalCount+0.0)/@PageSize)/2  --正向檢索
                        BEGIN
                            SET @Sql = 'SELECT TOP ' + STR(@PageSize) + ' ' + @FieldList + ' FROM ( '
                                       + 'SELECT TOP ' + STR(@PageSize) + ' ' + @FieldList + ' FROM ( '
                                       + ' SELECT TOP ' + STR(@PageSize*@PageIndex) + ' ' + @FieldList
                                       + ' FROM ' + @TableName + @new_where1 + @new_order1 + ' ) AS TMP '
                                       + @new_order2 + ' ) AS TMP ' + @new_order1    
                        END
                    ELSE  --反向檢索
                        BEGIN
                            SET @Sql = 'SELECT TOP ' + STR(@PageSize) + ' ' + @FieldList + ' FROM ( '  
                                       + 'SELECT TOP ' + STR(@PageSize) + ' ' + @FieldList + ' FROM ( '
                                       + ' SELECT TOP ' + STR(@TotalCount-@PageSize*@PageIndex+@PageSize) + ' ' + @FieldList
                                       + ' FROM ' + @TableName + @new_where1 + @new_order2 + ' ) AS TMP '
                                       + @new_order1 + ' ) AS TMP ' + @new_order1
                        END
                END
        END
    PRINT(@Sql)
    EXEC(@Sql)

SqlHelper.cs資料庫操作類程式碼如下:

using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Reflection;
using System.Runtime.Serialization.Formatters.Binary;
using System.Xml;


/// <summary>
/// 資料庫訪問抽象基類  (基於MS-SQLServer2005或以上版本)
/// 此類為抽象類 abstract ,不允許例項化,在應用時直接呼叫即可
/// </summary>
public abstract class SqlHelper
{
    //資料庫連線字串(web.config來配置),可以動態更改connectionString支援多資料庫.		
    public static readonly string LocalSqlServer = System.Configuration.ConfigurationManager.AppSettings["ConnectionString"].ToString();

    #region ===========通用分頁儲存過程===========
    /// <summary>
    /// 通用分頁儲存過程
    /// </summary>
    /// <param name="connectionString"></param>
    /// <param name="tblName"></param>
    /// <param name="strGetFields"></param>
    /// <param name="primaryKey"></param>
    /// <param name="strWhere"></param>
    /// <param name="strOrder"></param>
    /// <param name="sortType"></param>
    /// <param name="recordCount"></param>
    /// <param name="PageSize"></param>
    /// <param name="PageIndex"></param>
    /// <param name="totalCount"></param>
    /// <param name="totalPageCount"></param>
    /// <returns></returns>
    public static DataSet PageList(string connectionString, string tblName, string strGetFields, string primaryKey, string strWhere, string strOrder, int sortType, int recordCount,
        int PageSize, int PageIndex,ref int totalCount,ref int totalPageCount)
    {
        SqlParameter[] parameters ={ new SqlParameter("@TableName ",SqlDbType.VarChar,200),
                new SqlParameter("@FieldList",SqlDbType.VarChar,2000),
                new SqlParameter("@PrimaryKey",SqlDbType.VarChar,100),
                new SqlParameter("@Where",SqlDbType.VarChar,2000),
                new SqlParameter("@Order",SqlDbType.VarChar,1000),
                new SqlParameter("@SortType",SqlDbType.Int),
                new SqlParameter("@RecorderCount",SqlDbType.Int),
                new SqlParameter("@PageSize",SqlDbType.Int),
                new SqlParameter("@PageIndex",SqlDbType.Int),
                new SqlParameter("@TotalCount",SqlDbType.Int),
                new SqlParameter("@TotalPageCount",SqlDbType.Int)};

        parameters[0].Value = tblName;
        parameters[1].Value = strGetFields;
        parameters[2].Value = primaryKey;
        parameters[3].Value = strWhere;
        parameters[4].Value = strOrder;
        parameters[5].Value = sortType;
        parameters[6].Value = recordCount;
        parameters[7].Value = PageSize;
        parameters[8].Value = PageIndex;
        parameters[9].Value = totalCount;
        parameters[9].Direction = ParameterDirection.Output;
        parameters[10].Value = totalPageCount;
        parameters[10].Direction = ParameterDirection.Output;

        DataSet ds = RunProcedureDS(connectionString, "P_viewPage", parameters, "PageListTable");
        totalCount = int.Parse(parameters[9].Value.ToString());
        totalPageCount = int.Parse(parameters[10].Value.ToString());
        return ds;
    }
    #endregion

    #region ===========執行簡單SQL語句============

    /// <summary>
    /// 獲取表某個欄位的最大值
    /// </summary>
    /// <param name="FieldName"></param>
    /// <param name="TableName"></param>
    /// <returns></returns>
    public static int GetMaxID(string connectionString, string FieldName, string TableName)
    {
        string strSql = "select max(" + FieldName + ") from " + TableName;
        DataSet ds = ExecuteDataSet(connectionString, strSql);
        if (ds.Tables[0].Rows[0][0] != DBNull.Value)
        {
            return int.Parse(ds.Tables[0].Rows[0][0].ToString());
        }
        else
        {
            return 0;
        }
    }

    /// <summary>
    ///  檢測一個記錄是否存在(SqlParameter語句方式)
    /// </summary>
    /// <param name="strSql"></param>
    /// <param name="cmdParms"></param>
    /// <returns></returns>
    public static bool ExistsRecord(string connectionString, string strSql, params SqlParameter[] cmdParms)
    {
        DataSet ds = RunProcedureDS(connectionString, strSql, cmdParms);
        return int.Parse(ds.Tables[0].Rows[0][0].ToString()) > 0;
    }


    /// <summary>
    ///執行查詢,並將查詢返回的結果集中第一行的第一列作為 .NET Framework 資料型別返回。忽略額外的列或行。返回查詢結果(object)。
    /// </summary>
    /// <param name="SQLString">計算查詢結果語句</param>
    /// <returns>查詢結果(object)</returns>
    public static object GetSingle(string connectionString, string SQLString)
    {
        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            using (SqlCommand cmd = new SqlCommand(SQLString, connection))
            {
                try
                {
                    connection.Open();
                    object obj = cmd.ExecuteScalar();
                    if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
                    {
                        return null;
                    }
                    else
                    {
                        return obj;
                    }
                }
                catch (System.Data.SqlClient.SqlException e)
                {
                    connection.Close();
                    throw new Exception(e.Message);
                }
            }
        }
    }

    #endregion 執行簡單SQL語句

    #region StrSQL執行結果,返回執行後受影響的行數

    /*【公告】:ExecuteNonQuery()方法介紹
         *對於   UPDATE、INSERT   和   DELETE   語句,
         *返回值為該命令所影響的行數。對於所有其他型別的語句,
         *返回值為   -1。如果發生回滾,返回值也為   -1。
         */

    /// <summary>
    /// 執行SQL語句,返回影響的記錄數,select型別的語句此方法不可行。
    /// 對於select方法應該通過Dataset.Tables[0].Rows.Count來判斷
    /// </summary>
    /// <param name="SQLString">SQL語句</param>
    /// <returns>影響的記錄數</returns>
    public static int ExecuteSql(string connectionString, string SQLString)
    {
        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            using (SqlCommand cmd = new SqlCommand(SQLString, connection))
            {
                try
                {
                    connection.Open();
                    int rows = cmd.ExecuteNonQuery();
                    return rows;
                }
                catch (System.Data.SqlClient.SqlException E)
                {
                    connection.Close();
                    throw new Exception(E.Message);
                }
            }
        }
    }
    /// <summary>
    /// 方法過載,限定查詢時間,返回影響的記錄數
    /// 客觀的多併發查詢時,可限制使用者查詢時間,以免對伺服器增加負擔
    /// </summary>
    /// <param name="Times">等待命令執行的時間,預設值為 30 秒。</param>
    /// <returns>影響的記錄數</returns>
    public static int ExecuteSql(string connectionString, string SQLstring, int Times)
    {
        using (SqlConnection conntion = new SqlConnection(connectionString))
        {
            using (SqlCommand cmd = new SqlCommand(SQLstring, conntion))
            {
                try
                {
                    conntion.Open();
                    cmd.CommandTimeout = Times;//預設值為 30 秒
                    int rows = cmd.ExecuteNonQuery();
                    return rows;
                }
                catch (System.Data.SqlClient.SqlException e)
                {
                    conntion.Close();
                    throw e;
                }
            }
        }
    }

    /// <summary>
    /// 執行SQL語句,返回記錄的條數【注意是記錄數】;
    /// 獲取SQL欄位第一行第一欄位的數值,請不要用select
    /// </summary>
    /// <param name="SQLString">SQL語句</param>
    /// <returns>影響的記錄數</returns>
    public static int ExecuteCountSql(string connectionString, string SQLString)
    {
        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            using (SqlCommand cmd = new SqlCommand(SQLString, connection))
            {
                try
                {
                    connection.Open();
                    SqlDataReader dr = cmd.ExecuteReader();
                    dr.Read();
                    int count = int.Parse(dr[0].ToString());
                    return count;

                }
                catch (System.Data.SqlClient.SqlException E)
                {
                    connection.Close();
                    throw new Exception(E.Message);
                }
            }
        }
    }

    /// <summary>
    /// 執行帶一個儲存過程引數的的SQL語句。
    /// </summary>
    /// <param name="SQLString">SQL語句</param>
    /// <param name="content">引數內容,比如一個欄位是格式複雜的文章,有特殊符號,可以通過這個方式新增</param>
    /// <returns>影響的記錄數</returns>
    public static int ExecuteSql(string connectionString, string SQLString, string content)
    {
        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            SqlCommand cmd = new SqlCommand(SQLString, connection);
            SqlParameter myParameter = new SqlParameter("@content", SqlDbType.NText);
            myParameter.Value = content;
            cmd.Parameters.Add(myParameter);
            try
            {
                connection.Open();
                int rows = cmd.ExecuteNonQuery();
                return rows;
            }
            catch (SqlException E)
            {
                throw new Exception(E.Message);
            }
            finally
            {
                cmd.Dispose();
            }
        }
    }

    /// <summary>
    /// 向資料庫裡插入影象格式的欄位(和上面情況類似的另一種例項)
    /// </summary>
    /// <param name="strSQL">SQL語句</param>
    /// <param name="fs">影象位元組,資料庫的欄位型別為image的情況</param>
    /// <returns>影響的記錄數</returns>
    public static int ExecuteSqlInsertImg(string connectionString, string strSQL, byte[] fs)
    {
        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            SqlCommand cmd = new SqlCommand(strSQL, connection);
            SqlParameter myParameter = new SqlParameter("@fs", SqlDbType.Image);
            myParameter.Value = fs;
            cmd.Parameters.Add(myParameter);
            try
            {
                connection.Open();
                int rows = cmd.ExecuteNonQuery();
                return rows;
            }
            catch (SqlException E)
            {
                throw new Exception(E.Message);
            }
            finally
            {
                cmd.Dispose();
            }
        }
    }

    /// <summary>
    /// 執行帶引數的SQL語句,返回影響的記錄數
    /// </summary>
    /// <param name="connectionString">連線字串</param>
    /// <param name="SQLString">SQL語句</param>
    /// <param name="cmdParms">引數</param>
    /// <returns>影響的記錄數</returns>
    public static int ExecuteSql(string connectionString, string SQLString, params SqlParameter[] cmdParms)
    {
        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            using (SqlCommand cmd = new SqlCommand())
            {
                try
                {
                    PrepareCommand(cmd, connection, null, SQLString, cmdParms);
                    int rows = cmd.ExecuteNonQuery();
                    cmd.Parameters.Clear();
                    return rows;
                }
                catch (System.Data.SqlClient.SqlException E)
                {
                    connection.Close();
                    throw new Exception(E.Message);
                }
            }
        }
    }

    /// <summary>
    /// 執行儲存過程,返回Return值【這個方法還沒看明白,- -  】
    /// </summary>
    /// <param name="storedProcName">儲存過程名</param>
    /// <param name="parameters">儲存過程引數</param>
    /// <param name="rowsAffected">影響的行數</param>
    /// <returns></returns>
    public static int RunProcedure(string connectionString, string storedProcName, IDataParameter[] parameters, out int rowsAffected)
    {
        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            int result;
            connection.Open();
            SqlCommand command = BuildIntCommand(connection, storedProcName, parameters);
            rowsAffected = command.ExecuteNonQuery();
            result = (int)command.Parameters["ReturnValue"].Value;
            connection.Close();
            return result;
        }
    }
    #endregion

    #region ============獲取DataReader============

    /*【公告】下面的方法呼叫(先例項化一個dr)該方法後,
         * 一定要對SqlDataReader進行Close (對例項化的dr進行 dr.Close();
         * 如果不Close掉,則會保持read回話狀態,加重資料庫負荷) */

    /// <summary>
    /// 執行查詢語句,返回SqlDataReader
    /// </summary>
    /// <param name="strSQL">查詢語句</param>
    /// <returns>SqlDataReader</returns>
    public static SqlDataReader ExecuteReader(string connectionString, string strSQL)
    {
        SqlConnection connection = new SqlConnection(connectionString);
        SqlCommand cmd = new SqlCommand(strSQL, connection);
        try
        {
            connection.Open();
            SqlDataReader myReader = cmd.ExecuteReader();
            return myReader;
        }
        catch (System.Data.SqlClient.SqlException e)
        {
            throw new Exception(e.Message);
        }
        finally
        {
            connection.Close();
        }
    }

    /// <summary>
    /// 執行儲存過程,返回SqlDataReader 
    /// </summary>
    /// <param name="storedProcName">儲存過程名</param>
    /// <param name="parameters">儲存過程引數</param>
    /// <returns>SqlDataReader</returns>
    public static SqlDataReader RunProcedureDR(string connectionString, string storedProcName, IDataParameter[] parameters)
    {
        SqlConnection connection = new SqlConnection(connectionString);
        SqlDataReader returnReader;
        try
        {
            connection.Open();
            SqlCommand command = BuildQueryCommand(connection, storedProcName, parameters);
            command.CommandType = CommandType.StoredProcedure;
            returnReader = command.ExecuteReader(CommandBehavior.CloseConnection);
        }
        catch (System.Data.SqlClient.SqlException e)
        {
            connection.Close();
            throw new Exception(e.Message);
        }
        return returnReader;
    }
    #endregion

    #region =============獲取DataSet==============

    /// <summary>
    /// 執行查詢語句,返回DataSet
    /// </summary>
    /// <param name="SQLString">查詢語句</param>
    /// <returns>DataSet</returns>
    public static DataSet ExecuteDataSet(string connectionString, string SQLString)
    {
        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            DataSet ds = new DataSet();
            try
            {
                connection.Open();

                SqlDataAdapter command = new SqlDataAdapter(SQLString, connection);
                command.Fill(ds);
            }
            catch (SqlException ex)
            {
                connection.Close();
                throw new Exception(ex.Message);
            }
            return ds;
        }
    }
    public static DataSet ExecuteDataSet(string connectionString, string strSQL, int Times)
    {
        using (SqlConnection conntion = new SqlConnection(connectionString))
        {
            DataSet ds = new DataSet();
            try
            {
                conntion.Open();
                SqlDataAdapter da = new SqlDataAdapter(strSQL, conntion);
                da.SelectCommand.CommandTimeout = Times;//限制查詢時間
                da.Fill(ds);
            }
            catch (System.Data.SqlClient.SqlException e)
            {
                conntion.Close();
                throw new Exception(e.Message);
            }
            return ds;
        }
    }

    /// <summary>
    /// 執行查詢語句,返回DataSet
    /// </summary>
    /// <param name="SQLString">查詢語句</param>
    /// <returns>DataSet</returns>
    /// BU層得到物件實體用這個方法
    public static DataSet ExecuteDataSet(string connectionString, string SQLString, params SqlParameter[] cmdParms)
    {
        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            SqlCommand cmd = new SqlCommand();
            PrepareCommand(cmd, connection, null, SQLString, cmdParms);
            using (SqlDataAdapter da = new SqlDataAdapter(cmd))
            {
                DataSet ds = new DataSet();
                try
                {
                    da.Fill(ds);
                    cmd.Parameters.Clear();
                }
                catch (System.Data.SqlClient.SqlException ex)
                {
                    throw new Exception(ex.Message);
                }
                return ds;
            }
        }
    }

    //【呼叫方法】:
    //ArrayList arrayList = new ArrayList();
    //arrayList.Add("strsql1");
    //arrayList.Add("strsql2");
    //...
    //arrayList.Add("strsqln");
    //return DbHelperSQL.ExecuteManySqlDS(arrayList);         
    /// <summary>
    /// 執行多條SQL語句返回多個DataSet
    /// </summary>
    /// <param name="arrayList">arrayList物件集合</param>
    /// <returns>多個資料集</returns>
    public static DataSet ExecuteManySqlDS(string connectionString, ArrayList arrayList)
    {
        DataSet set = new DataSet();
        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            SqlCommand command = new SqlCommand();
            command.Connection = connection;
            string table = "table";
            SqlDataAdapter adapter = new SqlDataAdapter();

            for (int i = 0; i < arrayList.Count; ++i)
            {
                command.CommandText = arrayList[i].ToString();
                adapter.SelectCommand = command;
                adapter.Fill(set, table + i);// table + i 每個語句返回資料集的表名
            }
            return set;
        }
    }

    /// <summary>
    /// 執行儲存過程返回DataSet
    /// </summary>
    /// <param name="storedProcName">儲存過程名</param>
    /// <param name="parameters">儲存過程引數</param>
    /// <param name="tableName">DataSet結果中的表名</param>
    /// <returns>DataSet</returns>
    public static DataSet RunProcedureDS(string connectionString, string storedProcName, IDataParameter[] parameters)
    {
        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            DataSet dataSet = new DataSet();
            try
            {
                connection.Open();
                SqlDataAdapter sqlDA = new SqlDataAdapter();
                sqlDA.SelectCommand = BuildQueryCommand(connection, storedProcName, parameters);
                sqlDA.Fill(dataSet);
            }
            catch (System.Data.SqlClient.SqlException e)
            {
                connection.Close();
                throw new Exception(e.Message);
            }
            return dataSet;
        }
    }
    public static DataSet RunProcedureDS(string connectionString, string storedProcName, IDataParameter[] parameters, string tableName)
    {
        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            DataSet dataSet = new DataSet();
            connection.Open();
            SqlDataAdapter sqlDA = new SqlDataAdapter();
            sqlDA.SelectCommand = BuildQueryCommand(connection, storedProcName, parameters);
            sqlDA.Fill(dataSet, tableName);
            connection.Close();
            return dataSet;
        }
    }
    #endregion

    #region ============資料庫事務處理============
    /// <summary>
    /// 執行多條SQL語句,實現資料庫事務
    /// </summary>
    /// <param name="SQLStringList">多條SQL語句</param>
    /// <returns>執行事務影響的行數</returns>
    public static int ExecuteSqlTran(string connectionString, List<String> SQLStringList)
    {
        using (SqlConnection conntion = new SqlConnection(connectionString))
        {
            conntion.Open();
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = conntion;

            SqlTransaction ts = conntion.BeginTransaction();
            cmd.Transaction = ts;
            try
            {
                int count = 0;
                for (int n = 0; n < SQLStringList.Count; n++)
                {
                    string strsql = SQLStringList[n];
                    if (strsql.Length > 1)
                    {
                        cmd.CommandText = strsql;
                        count += cmd.ExecuteNonQuery();
                    }
                }
                ts.Commit();//提交資料庫事務
                return count;
            }
            catch
            {
                ts.Rollback();
                return 0;
            }
        }
    }

    /// <summary>
    ///  執行多條SQL語句,實現資料庫事務
    /// </summary>
    /// <param name="SQLStringList">SQL語句的雜湊表(key為sql語句,value是該語句的SqlParameter[])</param>
    public static void ExecuteSqlTran(string connectionString, Hashtable SQLStringList)
    {
        using (SqlConnection conn = new SqlConnection(connectionString))
        {
            conn.Open();
            using (SqlTransaction trans = conn.BeginTransaction())
            {
                SqlCommand cmd = new SqlCommand();
                try
                {
                    //迴圈
                    foreach (DictionaryEntry myDY in SQLStringList)
                    {
                        string cmdText = myDY.Key.ToString();
                        SqlParameter[] parameter = (SqlParameter[])myDY.Value;
                        PrepareCommand(cmd, conn, trans, cmdText, parameter);
                        int result = cmd.ExecuteNonQuery();     //這裡可以記錄該事務的執行結果
                        cmd.Parameters.Clear();
                    }
                    trans.Commit();
                }
                catch
                {
                    trans.Rollback();
                    throw;
                }
            }
        }
    }

    #endregion

    #region 建立 SqlCommand 物件及建立執行命令引數

    /// <summary>
    /// 為執行命令準備引數
    /// </summary>
    /// <param name="cmd">SqlCommand 命令</param>
    /// <param name="conn">已經存在的資料庫連線</param>
    /// <param name="trans">資料庫事物處理</param>
    /// <param name="cmdText">SQL語句</param>
    /// <param name="cmdparams">返回帶引數的命令</param>
    public static void PrepareCommand(SqlCommand cmd, SqlConnection conn, SqlTransaction trans, string cmdText, SqlParameter[] cmdparams)
    {
        if (conn.State != ConnectionState.Open)
        {//判斷資料庫連線狀態
            conn.Open();
        }
        cmd.Connection = conn;
        cmd.CommandText = cmdText;
        if (trans != null)
        {//判斷是否需要事物處理
            cmd.Transaction = trans;
        }
        cmd.CommandType = CommandType.Text;
        if (cmdparams != null)
        {
            foreach (SqlParameter parameter in cmdparams)
            {
                if ((parameter.Direction == ParameterDirection.InputOutput || parameter.Direction == ParameterDirection.Input) && (parameter.Value == null))
                {
                    parameter.Value = DBNull.Value;
                }
                cmd.Parameters.Add(parameter);
            }
        }
    }

    /// <summary>
    /// 建立 SqlCommand 物件例項(用來返回一個整數值)	
    /// </summary>
    /// <param name="storedProcName">儲存過程名</param>
    /// <param name="parameters">儲存過程引數</param>
    /// <returns>SqlCommand 物件例項</returns>
    private static SqlCommand BuildIntCommand(SqlConnection connection, string storedProcName, IDataParameter[] parameters)
    {
        SqlCommand command = BuildQueryCommand(connection, storedProcName, parameters);
        command.Parameters.Add(new SqlParameter("ReturnValue",
            SqlDbType.Int, 4, ParameterDirection.ReturnValue,
            false, 0, 0, string.Empty, DataRowVersion.Default, null));
        return command;
    }
    /// <summary>
    /// 構建 SqlCommand 物件(用來返回一個結果集,而不是一個整數值)
    /// </summary>
    /// <param name="connection">資料庫連線</param>
    /// <param name="storedProcName">儲存過程名</param>
    /// <param name="parameters">儲存過程引數</param>
    /// <returns>SqlCommand</returns>
    private static SqlCommand BuildQueryCommand(SqlConnection connection, string storedProcName, IDataParameter[] parameters)
    {
        SqlCommand command = new SqlCommand(storedProcName, connection);
        command.CommandType = CommandType.StoredProcedure;
        foreach (SqlParameter parameter in parameters)
        {
            if (parameter != null)
            {
                // 檢查未分配值的輸出引數,將其分配以DBNull.Value.
                if ((parameter.Direction == ParameterDirection.InputOutput || parameter.Direction == ParameterDirection.Input) &&
                    (parameter.Value == null))
                {
                    parameter.Value = DBNull.Value;
                }
                command.Parameters.Add(parameter);
            }
        }

        return command;
    }

    #endregion

    #region ============構造語句常用類============
    /// <summary>
    /// Make input param.
    /// </summary>
    /// <param name="ParamName">Name of param.</param>
    /// <param name="DbType">Param type.</param>
    /// <param name="Size">Param size.</param>
    /// <param name="Value">Param value.</param>
    /// <returns>New parameter.</returns>
    public static SqlParameter MakeInParam(string ParamName, SqlDbType DbType, int Size, object Value)
    {
        return MakeParam(ParamName, DbType, Size, ParameterDirection.Input, Value);
    }
    public static SqlParameter MakeInParam(string ParamName, SqlDbType DbType, object Value)
    {
        return MakeParam(ParamName, DbType, 0, ParameterDirection.Input, Value);
    }

    /// <summary>
    /// Make input param.
    /// </summary>
    /// <param name="ParamName">Name of param.</param>
    /// <param name="DbType">Param type.</param>
    /// <param name="Size">Param size.</param>
    /// <returns>New parameter.</returns>
    public static SqlParameter MakeOutParam(string ParamName, SqlDbType DbType, int Size)
    {
        return MakeParam(ParamName, DbType, Size, ParameterDirection.Output, null);
    }

    /// <summary>
    /// 構建儲存過程引數
    /// </summary>
    /// <param name="ParamName">引數名</param>
    /// <param name="DbType">引數型別(列舉)</param>
    /// <param name="Size">引數大小</param>
    /// <param name="Direction">DataSet 的引數型別(列舉)</param>
    /// <param name="Value">設定該引數的數值</param>
    /// <returns>New parameter.</returns>
    public static SqlParameter MakeParam(string ParamName, SqlDbType DbType, Int32 Size, ParameterDirection Direction, object Value)
    {
        SqlParameter param;
        if (Size > 0)
        {
            param = new SqlParameter(ParamName, DbType, Size);
        }
        else
        {
            param = new SqlParameter(ParamName, DbType);
        }
        param.Direction = Direction;
        if (!(Direction == ParameterDirection.Output && Value == null))
        {
            param.Value = Value;
        }
        return param;
    }
    #endregion 構造語句常用類

    #region =============由Object取值=============
    /// <summary>
    /// 取得Int值
    /// </summary>
    /// <param name="obj"></param>
    /// <returns></returns>
    public static int GetInt(object obj)
    {
        if (obj.ToString() != "")
            return int.Parse(obj.ToString());
        else
            return 0;
    }

    /// <summary>
    /// 獲得Long值
    /// </summary>
    /// <param name="obj"></param>
    /// <returns></returns>
    public static long GetLong(object obj)
    {
        if (obj.ToString() != "")
            return long.Parse(obj.ToString());
        else
            return 0;
    }

    /// <summary>
    /// 取得Decimal值
    /// </summary>
    /// <param name="obj"></param>
    /// <returns></returns>
    public static decimal GetDecimal(object obj)
    {
        if (obj.ToString() != "")
            return decimal.Parse(obj.ToString());
        else
            return 0;
    }

    /// <summary>
    /// 取得Guid值
    /// </summary>
    /// <param name="obj"></param>
    /// <returns></returns>
    public static Guid GetGuid(object obj)
    {
        if (obj.ToString() != "")
            return new Guid(obj.ToString());
        else
            return Guid.Empty;
    }

    /// <summary>
    /// 取得DateTime值
    /// </summary>
    /// <param name="obj"></param>
    /// <returns></returns>
    public static DateTime GetDateTime(object obj)
    {
        if (obj.ToString() != "")
            return DateTime.Parse(obj.ToString());
        else
            return DateTime.MinValue;
    }

    /// <summary>
    /// 取得bool值
    /// </summary>
    /// <param name="obj"></param>
    /// <returns></returns>
    public static bool GetBool(object obj)
    {
        if (obj.ToString() == "1" || obj.ToString().ToLower() == "true")
            return true;
        else
            return false;
    }

    /// <summary>
    /// 取得byte[]
    /// </summary>
    /// <param name="obj"></param>
    /// <returns></returns>
    public static Byte[] GetByte(object obj)
    {
        if (obj.ToString() != "")
        {
            return (Byte[])obj;
        }
        else
            return null;
    }

    /// <summary>
    /// 取得string值
    /// </summary>
    /// <param name="obj"></param>
    /// <returns></returns>
    public static string GetString(object obj)
    {
        return obj.ToString();
    }
    #endregion

    #region ===========序列化與反序列化===========
    /// <summary>
    /// 序列化物件
    /// </summary>
    /// <param name="obj">要序列化的物件</param>
    /// <returns>返回二進位制</returns>
    public static byte[] SerializeModel(Object obj)
    {
        if (obj != null)
        {
            BinaryFormatter binaryFormatter = new BinaryFormatter();
            MemoryStream ms = new MemoryStream();
            byte[] b;
            binaryFormatter.Serialize(ms, obj);
            ms.Position = 0;
            b = new Byte[ms.Length];
            ms.Read(b, 0, b.Length);
            ms.Close();
            return b;
        }
        else
            return new byte[0];
    }

    /// <summary>
    /// 反序列化物件
    /// </summary>
    /// <param name="b">要反序列化的二進位制</param>
    /// <returns>返回物件</returns>
    public static object DeserializeModel(byte[] b, object SampleModel)
    {
        if (b == null || b.Length == 0)
            return SampleModel;
        else
        {
            object result = new object();
            BinaryFormatter binaryFormatter = new BinaryFormatter();
            MemoryStream ms = new MemoryStream();
            try
            {
                ms.Write(b, 0, b.Length);
                ms.Position = 0;
                result = binaryFormatter.Deserialize(ms);
                ms.Close();
            }
            catch { }
            return result;
        }
    }
    #endregion

    #region ==========Model與XML互相轉換==========
    /// <summary>
    /// Model轉化為XML的方法
    /// </summary>
    /// <param name="model">要轉化的Model</param>
    /// <returns></returns>
    public static string ModelToXML(object model)
    {
        XmlDocument xmldoc = new XmlDocument();
        XmlElement ModelNode = xmldoc.CreateElement("Model");
        xmldoc.AppendChild(ModelNode);

        if (model != null)
        {
            foreach (PropertyInfo property in model.GetType().GetProperties())
            {
                XmlElement attribute = xmldoc.CreateElement(property.Name);
                if (property.GetValue(model, null) != null)
                    attribute.InnerText = property.GetValue(model, null).ToString();
                else
                    attribute.InnerText = "[Null]";
                ModelNode.AppendChild(attribute);
            }
        }

        return xmldoc.OuterXml;
    }

    /// <summary>
    /// XML轉化為Model的方法
    /// </summary>
    /// <param name="xml">要轉化的XML</param>
    /// <param name="SampleModel">Model的實體示例,New一個出來即可</param>
    /// <returns></returns>
    public static object XMLToModel(string xml, object SampleModel)
    {
        if (string.IsNullOrEmpty(xml))
            return SampleModel;
        else
        {
            XmlDocument xmldoc = new XmlDocument();
            xmldoc.LoadXml(xml);

            XmlNodeList attributes = xmldoc.SelectSingleNode("Model").ChildNodes;
            foreach (XmlNode node in attributes)
            {
                foreach (PropertyInfo property in SampleModel.GetType().GetProperties())
                {
                    if (node.Name == property.Name)
                    {
                        if (node.InnerText != "[Null]")
                        {
                            if (property.PropertyType == typeof(System.Guid))
                                property.SetValue(SampleModel, new Guid(node.InnerText), null);
                            else
                                property.SetValue(SampleModel, Convert.ChangeType(node.InnerText, property.PropertyType), null);
                        }
                        else
                            property.SetValue(SampleModel, null, null);
                    }
                }
            }
            return SampleModel;
        }
    }
    #endregion
}







相關文章