自定義分頁排序

{
    Int32 PageSize = 0;
    Int32 PageCount, RecCount, CurrentPage, Pages;
    bool isSorting = false;  //True if the user is sorting a column
    int sortColumn;    //The column number the user is trying to sort
    int sortBand;
    string sortSequence = " ASC ";

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            PageSize = this.uwgKeyWord.DisplayLayout.Pager.PageSize;

            RecCount = Calc();

            //Record Page count.
            PageCount = RecCount / PageSize + OverPage();

            //ViewState["PageCounts"] = RecCount / PageSize - ModPage();
            ViewState["PageCounts"] = RecCount / PageSize;

            ViewState["PageIndex"] = 0;
            ViewState["JumpPages"] = PageCount;
            ViewState["Order"] = " ORDER BY ID ASC ";

            //TDataBind();
            InitData();
            this.CheckUserType();
        }
    }

    public Int32 OverPage()
    {
        PageSize = this.uwgKeyWord.DisplayLayout.Pager.PageSize;

        Int32 pages = 0;
        if (RecCount % PageSize != 0)
            pages = 1;
        else
            pages = 0;
        return pages;
    }

    public Int32 ModPage()
    {
        PageSize = this.uwgKeyWord.DisplayLayout.Pager.PageSize;

        Int32 pages = 0;
        if (RecCount % PageSize == 0 && RecCount != 0)
            pages = 1;
        else
            pages = 0;
        return pages;
    }

    public static Int32 Calc()
    {
        Int32 RecordCount = 0;
        SqlCommand MyCmd = new SqlCommand("select count(*) as co from failurelog ", MyCon());
        SqlDataReader dr = MyCmd.ExecuteReader();
        if (dr.Read())
            RecordCount = Int32.Parse(dr["co"].ToString());
        MyCmd.Connection.Close();
        return RecordCount;
    }

    public static Int32 Calc(string sqlSearch)
    {
        Int32 RecordCount = 0;
        SqlCommand MyCmd = new SqlCommand(sqlSearch, MyCon());
        SqlDataReader dr = MyCmd.ExecuteReader();
        if (dr.Read())
            RecordCount = Int32.Parse(dr["co"].ToString());
        MyCmd.Connection.Close();
        return RecordCount;
    }

    public static SqlConnection MyCon()
    {
        SqlConnection MyConnection = new SqlConnection(ConfigurationManager.AppSettings["ConnectionString"]);
        MyConnection.Open();
        return MyConnection;
    }

    #region Bind UltraWebGrid
    /// <summary>
    /// Bind data to UltraWebGrid.
    /// </summary>
    private void BindData()
    {
        string querySql = "";
        string sqlSearch = "";

        PageSize = this.uwgKeyWord.DisplayLayout.Pager.PageSize;

        if (!string.IsNullOrEmpty(QueryCondition()))
        {
            sqlSearch = "select Count(*) as co from failurelog " + QueryCondition();
            RecCount = Calc(sqlSearch);
            //Record Page count.
            PageCount = RecCount / PageSize + OverPage();
        }
        else
        {
            RecCount = Calc();
        }

        ViewState["PageCounts"] = RecCount / PageSize;

        CurrentPage = (int)ViewState["PageIndex"];
        Pages = (int)ViewState["PageCounts"];

        if (Pages == 0)
        {
            Pages = 1;
        }

        if (PageCount == 0)
        {
            PageCount = 1;
        }

        if (string.IsNullOrEmpty(QueryCondition()))
        {
            if (isSorting == true)
            {
                querySql = "SELECT [ID],[ErrorMessage],[Type],[date] FROM failurelog " + QueryCondition() + " WHERE id IN " +
                       " (SELECT TOP " + PageSize + " id FROM failurelog WHERE id NOT IN " +
                       " (SELECT TOP " + "0" + " id FROM failurelog " + ViewState["Order"] + ")" +
                         ViewState["Order"] + " ) " +
                         ViewState["Order"];
            }
            else
            {
                querySql = "SELECT [ID],[ErrorMessage],[Type],[date] FROM failurelog " + QueryCondition() + " WHERE id IN " +
                           " (SELECT TOP " + PageSize + " id FROM failurelog WHERE id NOT IN " +
                           " (SELECT TOP " + PageSize * CurrentPage + " id FROM failurelog " + ViewState["Order"] + ")" +
                             ViewState["Order"] + " ) " +
                             ViewState["Order"];
            }
            //querySql = "Select Top " + PageSize + " [ID],[ErrorMessage],[Type],[date] from failurelog " + QueryCondition() +
            //           " where id not in(select top " + PageSize * CurrentPage + " id from failurelog order by id asc) order by id asc";
        }
        else
        {
            if (isSorting == true)
            {
                querySql = "SELECT [ID],[ErrorMessage],[Type],[date] FROM failurelog " + QueryCondition() + " AND id IN " +
                      " (SELECT TOP " + PageSize + " id FROM failurelog WHERE id NOT IN " +
                      " (SELECT TOP " + "0" + " id FROM failurelog " + ViewState["Order"] + ")" +
                        ViewState["Order"] + " ) " +
                        ViewState["Order"];
            }
            else
            {
                querySql = "SELECT [ID],[ErrorMessage],[Type],[date] FROM failurelog " + QueryCondition() + " AND id IN " +
                           " (SELECT TOP " + PageSize + " id FROM failurelog WHERE id NOT IN " +
                           " (SELECT TOP " + PageSize * CurrentPage + " id FROM failurelog " + ViewState["Order"] + ")" +
                             ViewState["Order"] + " ) " +
                             ViewState["Order"];
            }
            // querySql = "Select Top " + PageSize + " [ID],[ErrorMessage],[Type],[date] from failurelog " + QueryCondition() +
            //" AND id not in(select top " + PageSize * CurrentPage + " id from failurelog order by id asc) order by id asc";
        }

        DataSet ds = DbHelperSQL.Query(querySql);

        uwgKeyWord.DataSource = ds;
        uwgKeyWord.DataBind();

        this.uwgKeyWord.DisplayLayout.Bands[0].Columns.FromKey("Delete").Width = 60;
        this.uwgKeyWord.DisplayLayout.Bands[0].Columns.FromKey("ID").Hidden = false;

        this.uwgKeyWord.DisplayLayout.Bands[0].Columns.FromKey("Icon").Width = 15;

        this.uwgKeyWord.DisplayLayout.Bands[0].Columns.FromKey("Index").AllowUpdate = AllowUpdate.No;
        this.uwgKeyWord.DisplayLayout.Bands[0].Columns.FromKey("Index").Width = 40;
        this.uwgKeyWord.DisplayLayout.Bands[0].Columns.FromKey("Index").AllowRowFiltering = false;
        this.uwgKeyWord.DisplayLayout.Bands[0].Columns.FromKey("Index").Header.Caption = "ID".ToString();
        this.uwgKeyWord.DisplayLayout.Bands[0].Columns.FromKey("Index").SortIndicator = SortIndicator.Disabled;

        this.uwgKeyWord.DisplayLayout.Bands[0].Columns.FromKey("Type").AllowRowFiltering = false;
        this.uwgKeyWord.DisplayLayout.Bands[0].Columns.FromKey("Type").Header.Caption = "Type";
        this.uwgKeyWord.DisplayLayout.Bands[0].Columns.FromKey("Type").Width = 60;
        this.uwgKeyWord.DisplayLayout.Bands[0].Columns.FromKey("Type").AllowUpdate = AllowUpdate.No;
        //this.uwgKeyWord.DisplayLayout.Bands[0].Columns.FromKey("ErrorMessage").Width = 300;
        this.uwgKeyWord.DisplayLayout.Bands[0].Columns.FromKey("ErrorMessage").AllowRowFiltering = false;
        this.uwgKeyWord.DisplayLayout.Bands[0].Columns.FromKey("ErrorMessage").Header.Caption = "ErrorMessage";
        this.uwgKeyWord.DisplayLayout.Bands[0].Columns.FromKey("ErrorMessage").AllowUpdate = AllowUpdate.No;
        //Set generate row auto
        uwgKeyWord.Columns[5].CellStyle.Wrap = true;
        //set the StationaryMargin (TableLayout becomes fixed)
        uwgKeyWord.DisplayLayout.StationaryMargins = Infragistics.WebUI.UltraWebGrid.StationaryMargins.HeaderAndFooter;
        //set the size of the width
        uwgKeyWord.Columns[5].Width = 150;
        //uwgKeyWord.Columns[3].Width = 20;

        this.uwgKeyWord.DisplayLayout.Bands[0].Columns.FromKey("Date").AllowRowFiltering = false;
        this.uwgKeyWord.DisplayLayout.Bands[0].Columns.FromKey("Date").Header.Caption = "Date";
        this.uwgKeyWord.DisplayLayout.Bands[0].Columns.FromKey("Date").AllowUpdate = AllowUpdate.No;
        this.uwgKeyWord.DisplayLayout.Bands[0].Columns.FromKey("Date").Width = 130;

        if (this.uwgKeyWord.DisplayLayout.Pager.CurrentPageIndex > this.uwgKeyWord.DisplayLayout.Pager.PageCount)
        {
            this.uwgKeyWord.DisplayLayout.Pager.CurrentPageIndex = this.uwgKeyWord.DisplayLayout.Pager.PageCount;
            this.uwgKeyWord.DataBind();
        }

        uwgKeyWord.DisplayLayout.Pager.CurrentPageIndex = CurrentPage + 1;

        if (RecCount == 0)
        {
            uwgKeyWord.DisplayLayout.Pager.CurrentPageIndex = 1;
        }

        uwgKeyWord.DisplayLayout.Pager.PageCount = Pages;

        //Set auto index of row
        Int32 CurrentPage2 = uwgKeyWord.DisplayLayout.Pager.CurrentPageIndex;
        Int32 Total = uwgKeyWord.DisplayLayout.Pager.PageCount;

        Int32 PageCount2 = this.uwgKeyWord.Rows.Count % uwgKeyWord.DisplayLayout.Pager.PageSize;
        if (CurrentPage2 == (Total))
        {
            if (this.uwgKeyWord.Rows.Count != 0)
            {
                for (int i = 1; i <= (PageCount2 == 0 ? 10 : PageCount2); i++)
                {
                    this.uwgKeyWord.Rows[i - 1].Cells.FromKey("Index").Text = Convert.ToString((CurrentPage2 - 1) * 10 + i);
                }
            }
        }
        else
        {
            if (CurrentPage2 == 0)
            {
                CurrentPage2 = 1;
            }

            for (int i = 1; i <= uwgKeyWord.DisplayLayout.Pager.PageSize; i++)
            {
                if (this.uwgKeyWord.Rows[i - 1] != null)
                {
                    this.uwgKeyWord.Rows[i - 1].Cells.FromKey("Index").Text = Convert.ToString((CurrentPage2 - 1) * 10 + i);
                }
            }
        }
    }
    #endregion

    #region uwgKeyWord_OnPageIndexChanged
    /// <summary>
    /// OnPageIndexChanged event of uwgKeyWord
    /// </summary>
    protected void uwgKeyWord_OnPageIndexChanged(object sender, Infragistics.WebUI.UltraWebGrid.PageEventArgs e)
    {
        ViewState["PageIndex"] = this.uwgKeyWord.DisplayLayout.Pager.CurrentPageIndex - 1;

        this.BindData();

    }
    #endregion

    override protected void OnInit(EventArgs e)
    {
        //
        // CODEGEN: This call is required by the ASP.NET Web Form Designer.
        //
        InitializeComponent();
        base.OnInit(e);
    }

    /// <summary>
    /// Required method for Designer support - do not modify
    /// </summary>
    private void InitializeComponent()
    {
        this.uwgKeyWord.SortColumn += new Infragistics.WebUI.UltraWebGrid.SortColumnEventHandler(this.uwgKeyWord_SortColumn);
    }

    #region Initialization
    /// <summary>
    /// Initialization of this page.
    /// </summary>
    private void InitData()
    {
        this.BindData();
    }
    #endregion

    #region Condition of query
    /// <summary>
    /// Condition of query
    /// </summary>
    private string QueryCondition()
    {
        string strCondition = "";
        if (!string.IsNullOrEmpty(wdcStartDate.Text.Trim()) && !string.IsNullOrEmpty(wdcEndDate.Text.Trim()))
        {
            strCondition = "CONVERT(varchar(10),date,120)>='" + Convert.ToDateTime(wdcStartDate.Text).ToString("yyyy-MM-dd") + "' and CONVERT(varchar(10),date,120)<='" + Convert.ToDateTime(wdcEndDate.Text).ToString("yyyy-MM-dd") + "'";
        }
        if (string.IsNullOrEmpty(wdcStartDate.Text.Trim()) && !string.IsNullOrEmpty(wdcEndDate.Text.Trim()))
        {
            strCondition = "  CONVERT(varchar(10),date,120) <='" + Convert.ToDateTime(wdcEndDate.Text).ToString("yyyy-MM-dd") + "'";
        }
        if (!string.IsNullOrEmpty(wdcStartDate.Text.Trim()) && string.IsNullOrEmpty(wdcEndDate.Text.Trim()))
        {
            strCondition = " CONVERT(varchar(10),date,120)>='" + Convert.ToDateTime(wdcStartDate.Text).ToString("yyyy-MM-dd") + "'";
        }
        if (!string.IsNullOrEmpty(strCondition.Trim()))
        {
            strCondition = "where " + strCondition;
        }
        return strCondition;
    }
    #endregion


    #region uwgKeyWord_SortColumn
    /// <summary>
    /// Sort event of uwgKeyWord
    /// </summary>
    private void uwgKeyWord_SortColumn(object sender, Infragistics.WebUI.UltraWebGrid.SortColumnEventArgs e)
    {
        this.isSorting = true;
        this.sortColumn = e.ColumnNo; //Keep track of which column is being sorted
        this.sortBand = e.BandNo; //Keep track of which band is being sorted.

        string sortColumnName = uwgKeyWord.Bands[this.sortBand].Columns[this.sortColumn].Key.ToString();

        //Determine the direction that the column should be sorted.  If the column is currently unsorted or
        //is currently sorted descending, then set sortAscending to true.  We will use this in the PreRender
        //event to determine how to set the sort indicator.
        if (uwgKeyWord.Bands[this.sortBand].Columns[this.sortColumn].SortIndicator == SortIndicator.Descending)
        {
            this.sortSequence = " DESC ";
        }

        //Only sort failurelog exists fields
        if (this.sortColumn >= 4 && this.sortColumn <= 6)
        {
            ViewState["Order"] = " ORDER BY " + "[" + sortColumnName + "]" + this.sortSequence;
        }

        BindData();
    }
    #endregion


    #region BtnDelete_Click
    /// <summary>
    /// Delete event of uwgKeyWord
    /// </summary>
    protected void BtnDelete_Click(object sender, EventArgs e)
    {
        TemplatedColumn Tc = (TemplatedColumn)this.uwgKeyWord.Bands[0].Columns.FromKey("Delete");
        foreach (UltraGridRow fRow in this.uwgKeyWord.DisplayLayout.Rows)
        {
            CellItem fItem = (CellItem)Tc.CellItems[fRow.Index];
            CheckBox cb = (CheckBox)(fItem.FindControl("cbDelete"));
            if (cb.Checked)
            {
                string deleteSql = "delete from failurelog where id='" + uwgKeyWord.Rows[fRow.Index].Cells.FromKey("ID").Value.ToString() + "'";
                DbHelperSQL.ExecuteSql(deleteSql);
            }
        }

        this.uwgKeyWord.Rows.Clear();

        this.BindData();
    }
    #endregion

    #region uwgKeyWord_InitializeRow1
    /// <summary>
    /// InitializeRow event of uwgKeyWord
    /// </summary>
    protected void uwgKeyWord_InitializeRow1(object sender, Infragistics.WebUI.UltraWebGrid.RowEventArgs e)
    {
        if (e.Row.Index != -1)
        {
            string Type = e.Row.Cells.FromKey("Type").Text;
            switch (Type)
            {
                case "Warning":
                    // Set Icon       
                    e.Row.Cells.FromKey("Icon").Style.BackgroundImage = "../images/event/warning.jpg";
                    break;
                case "Error":
                    e.Row.Cells.FromKey("Icon").Style.BackgroundImage = "../images/event/error.jpg";
                    break;
                case "Information":
                    e.Row.Cells.FromKey("Icon").Style.BackgroundImage = "../images/event/information.jpg";
                    break;
            }
        }
    }
    #endregion

    #region uwgKeyWord_InitializeLayout
    /// <summary>
    /// InitializeLayout event of uwgKeyWord
    /// </summary>
    protected void uwgKeyWord_InitializeLayout(object sender, LayoutEventArgs e)
    {
        //uwgKeyWord.DisplayLayout.AllowSortingDefault = Infragistics.WebUI.UltraWebGrid.AllowSorting.Yes;
        //uwgKeyWord.DisplayLayout.HeaderClickActionDefault = Infragistics.WebUI.UltraWebGrid.HeaderClickAction.SortSingle;

        e.Layout.AllowSortingDefault = AllowSorting.Yes;
        e.Layout.HeaderClickActionDefault = HeaderClickAction.SortSingle;

    }
    #endregion

    #region BtnSearch_Click
    /// <summary>
    /// Search_Click event of uwgKeyWord
    /// </summary>
    protected void BtnSearch_Click(object sender, EventArgs e)
    {
        this.BindData();
    }
    #endregion

    #region Checks user whether have this authority.
    /// <summary>
    /// Checks user whether have this authority.
    /// </summary>
    private void CheckUserType()
    {
        FaxProcessor.BLL.Accounts bAccounts = new FaxProcessor.BLL.Accounts();
        if (this.Session["AccountInfo"] == null || bAccounts.GetModel(this.Session["AccountInfo"].ToString()).UserType != "admin")
        {
            Response.Write("<script language='javascript'>window.parent.location.replace('../login.aspx');</script>");
        }
    }
    #endregion

    protected void btnDeleteAll_Click(object sender, EventArgs e)
    {
        string sqlDeleteAll = "delete from failurelog ";
        DbHelperSQL.ExecuteSql(sqlDeleteAll);
        this.BindData();
    }

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章