GridView 分页代码 排序代码 分页排序 隔行换色

前台:

<!--样式,隔行换色-->

<style type="text/css">

.gridview
{
    border:0;
    background-color:#ccc;/*网格颜色*/
}
.gridview th
{
    border: 0;
    background-color:#eee;
    line-height:200%;
}
.gridview tr
{
    background-color:White
}
.gridview td
{
    padding: 6px 4px;
    border:0;
}
.gridview .dgItem:hover
{
background-color:#f4fc6e;

}
.gridview .dgAlter
{
    background-color: #f0f8ff;
}
.gridview .dgAlter:hover
{
background-color:#f4fc6e;
}

</style>

     <script language="javascript" type="text/javascript">
        function setPageIndex(pageindex) {
            document.getElementById('litPageIndex').value = pageindex;
        }
    </script>

    <div>
        <input type="hidden" id="litPageIndex" runat="server" />
        <span style="float: left">查找结果:共<%=recordCount%>个</span>
        <span style="float: right; margin-right: 0px">总页数:<%=pageCount %>&nbsp;&nbsp;
           <span onclick="setPageIndex(<%= pageIndex-1 %>)"><a runat="server" onserverclick="GoToPage">前一页</a></span>
           <span onclick="setPageIndex(<%= pageIndex+1 %>)"><a runat="server" onserverclick="GoToPage">后一页</a></span>&nbsp;当前页:
            <input type="text" id="txtPInd1" value="<%=pageIndex %>" size="4" />
            <asp:Button runat="server" OnClientClick="setPageIndex(document.getElementById('txtPInd1').value)" OnClick="GoToPage" Text="Go" />
           </span>
     </div>

    <div>
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" CssClass="gridview"
            CellPadding="2" CellSpacing="1" GridLines="None" AlternatingRowStyle-CssClass="dgAlter" OnRowDataBound="GridView1_RowDataBound" OnRowCommand="GridView1_RowCommand" >
            <RowStyle CssClass="dgItem" />
            <Columns>
                <asp:TemplateField HeaderText="上线时间">
                    <HeaderTemplate>
                        <asp:LinkButton ID="lbAddDate" runat="server" CommandName="Sort" CommandArgument="AddDate,Desc">上线时间</asp:LinkButton>
                    </HeaderTemplate>
                    <ItemTemplate>
                        <asp:Label ID="AddDate" runat="server" Text='<%# Convert.ToDateTime(DataBinder.Eval(Container.DataItem, "AddDate")).ToString("yyyy-MM-dd HH:mm:ss") %>'></asp:Label>
                    </ItemTemplate>
                    <ItemStyle HorizontalAlign="Center" Width="80px" />
                </asp:TemplateField>


                <asp:TemplateField HeaderText="章节数">
                    <HeaderTemplate>
                        <asp:LinkButton ID="lbChaptersCount" runat="server" CommandName="Sort" CommandArgument="ChaptersCount,Desc">章节数</asp:LinkButton>
                    </HeaderTemplate>
                    <ItemTemplate>
                        <asp:Label ID="Chapters" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "ChaptersCount") %>'></asp:Label>
                    </ItemTemplate>
                    <ItemStyle HorizontalAlign="Center" Width="80px" />
                </asp:TemplateField>

            </Columns>
        </asp:GridView>
    </div>
    <div>
        <span style="float: left">查找结果:共<%=recordCount%>个</span> <span style="float: right; margin-right: 0px">
            总页数:<%=pageCount %>&nbsp;&nbsp; <span onclick="setPageIndex(<%= pageIndex-1 %>)"><a
                id="A1" runat="server" onserverclick="GoToPage">前一页</a></span> <span onclick="setPageIndex(<%= pageIndex+1 %>)">
                    <a id="A2" runat="server" onserverclick="GoToPage">后一页</a></span>&nbsp;当前页:
            <input type="text" id="txtPInd2" value="<%=pageIndex %>" size="4" />
            <asp:Button ID="Button1" runat="server" OnClientClick="setPageIndex(document.getElementById('txtPInd2').value)"
                OnClick="GoToPage" Text="Go" />
        </span>
    </div>

后台:

    private string SortExpression
    {
        get
        {
            if(ViewState["SortExpression"]+""=="")

            ViewState["SortExpression"]="AddDate";
            return ViewState["SortExpression"]+"";
        }
        set
        {
            ViewState["SortExpression"] = value;
        }
    }

    private string SortDirection
    {
        get
        {
            if (ViewState["SortDirection"] + "" == "")

                ViewState["SortDirection"] = "Desc";
            return ViewState["SortDirection"] + "";
        }
        set
        {
            ViewState["SortDirection"] = value;
        }
    }

    private string tempSortID
    {
        get
        {
            if (ViewState["tempSortID"] + "" == "")
                ViewState["tempSortID"] = "ldAddDate";
            return ViewState["tempSortID"] + "";
        }
        set
        {
            ViewState["tempSortID"] = value;
        }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
             if (Utility.IsNumber(litPageIndex.Value))
            {
                int.TryParse(litPageIndex.Value, out pageIndex);
            }
    }
    public int recordCount=0;
    public int pageIndex = 1;
    public int pageCount = 0;
    int pageSize = 20;

    protected void Search_Click(object sender, EventArgs e)
    {
        pageIndex = 1;
        BindData();
    }
    void BindData()
    {
        SqlParameter[] para ={ new SqlParameter("@KDateStart",SqlDbType.Date),
                                  new SqlParameter("@KDateEnd",SqlDbType.Date),
                                  new SqlParameter("@KType",SqlDbType.Int),
                                  new SqlParameter("@IsSuccess",SqlDbType.Bit)
                                };

        string sqlselect = "KWord,sum(KCount) as KCount";
        string sqlfrom = @" from KeyWord where 1=1";
        string sqlwhere = ""; 
        string sqlorder = string.Format(" order by {0} {1}", SortExpression, SortDirection);
        string sqlgroupby = " group by KWord";

        if (Sxmobi.Tools.IsDatetime(txtStartDate.Value))
        {
            para[0].Value = Convert.ToDateTime(txtStartDate.Value);
            sqlwhere += " and DateDiff(d,KDate,@KDateStart)<=0";
        }

        if (Sxmobi.Tools.IsDatetime(txtEndDate.Value))
        {
            para[1].Value = Convert.ToDateTime(txtEndDate.Value);
            sqlwhere += " and DateDiff(d,KDate,@KDateEnd)>=0";
        }

        if (Sxmobi.Tools.IsInt(selPID.Value))
        {
            para[2].Value = selPID.Value;
            sqlwhere += " and KType=@KType";
        }

        if (selStatus.Value!="")
        {
            para[3].Value = (selStatus.Value == "1") ? true : false;
            sqlwhere += " and  IsSuccess=@IsSuccess";
        }

        string sqlCount = "select count(0) from (select 0 as c " + sqlfrom + sqlwhere+ sqlgroupby+") t";
        object obj = Sxmobi.SqlHelper.ExecuteScalar(SiteConfig.DBConnectionString, CommandType.Text, sqlCount, para);
        recordCount = 0;
        int.TryParse(obj + "", out recordCount);


        if (recordCount> 0)
        {
            pageCount = recordCount/ pageSize;

            if (pageCount * pageSize < recordCount) pageCount++;

            if (pageIndex > pageCount)
            {
                Page.ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('已经是最后一页')</script>");
                pageIndex = pageCount;
            }
            if (pageIndex < 1)
            {
                Page.ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('已经是第一页')</script>");
                pageIndex = 1;
            }

            string sql = GetSqlByPage(sqlselect, sqlfrom, sqlwhere, sqlorder, sqlgroupby);
            DataTable dt = Sxmobi.SqlHelper.ExecuteDataTable(SiteConfig.DBConnectionString, CommandType.Text, sql, para);

            gv.DataSource = dt;
            gv.DataBind();
        }
        else
        {
            pageIndex = 0;
            pageCount = 0;
            gv.DataSource = null;
            gv.DataBind();
        }

        ShowPageMsg();


    }

    string GetSqlByPage(string sqlSelect, string sqlFrom, string sqlWhere, string sqlOrder, string sqlGroupby)
    {
        string sql = @"  SELECT TOP " + pageSize + @" *
FROM
        (
        SELECT ROW_NUMBER() OVER (" + sqlOrder + ") AS RowNumber," + sqlSelect + sqlFrom + sqlWhere + sqlGroupby + @"
        ) Ab
WHERE RowNumber > " + pageSize * (pageIndex - 1) + " order by RowNumber"; 

       return sql;
    }

      void ShowPageMsg()
      {
          litPageIndex.Value = pageIndex>0?pageIndex.ToString():"";
      }

    protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "Sort")
        {
            string[] str = e.CommandArgument.ToString().Split(',');
            SortExpression = str[0];
            SortDirection = str[1];
            if (SortDirection == "") SortDirection = "Desc";
            LinkButton lb = (LinkButton)e.CommandSource;
            tempSortID = lb.ID;
            pageIndex = 1;
            BindData();
        }
    }

   protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {

        if (e.Row.RowType == DataControlRowType.Header)
        {
            if (tempSortID != "")
            {
                if (e.Row.FindControl(tempSortID) != null)
                {
                    LinkButton lb = (LinkButton)e.Row.FindControl(tempSortID);
                    lb.CommandArgument = SortExpression + ",AscDesc".Replace(SortDirection, "");//改变排序方向
                    string arrow = (SortDirection.ToUpper() == "ASC") ? "↑" : "↓";
                    lb.Text = arrow + lb.Text;
                }
            }
        }
    }

    protected void GoToPage(object sender, EventArgs e)
    {
        BindData();

    }

 转载请注明出处:http://blog.csdn.net/dasihg/article/details/6781375

原文地址:https://www.cnblogs.com/dashi/p/4034781.html