1

我有一个执行自定义查询的页面,该查询保存在数据库的某个位置。我需要能够在 gridview 上启用分页。

例如,保存在数据库中的查询如下所示:

select * from requestbases

这将返回 10,000 行。

使用下面的方法,我让它返回 10 行。

public DataTable GetGenericResults(string strsql, int pageIndex)
{
   StringBuilder sb = new StringBuilder();
   sb.Append("WITH MyPagedData as ( ");
   int indexFrom = strsql.IndexOf("from");
   sb.Append(strsql.Substring(0, indexFrom));
   sb.Append(", ");
   sb.Append("ROW_NUMBER() OVER(ORDER BY RequestBaseId DESC) as RowNum ");
   sb.Append(strsql.Substring(indexFrom));
   sb.Append(") ");
   sb.Append("SELECT * from MyPagedData where RowNum between @StartIndex and @StartIndex + 10");

   using(var connection = (SqlConnection)_context.Database.Connection)
   {
      var adapter = new SqlDataAdapter(sb.ToString(), connection);
      adapter.SelectCommand.Parameters.Add("@StartIndex", SqlDbType.Int).Value = pageIndex;
      var results = new DataSet();
      adapter.Fill(results, "Results");
      return results.Tables["Results"];
   }
}

这是绑定网格的代码

var datatable = RequestBaseBL.GetGenericResults(query.QuerySql, 0);

if (datatable.Rows.Count > 0)
{
    LblCount.Text = datatable.Rows.Count + " records";
    PanelResults.Visible = true;
    GrvCustomResults.Visible = true;
    GrvCustomResults.DataSource = datatable;
    GrvCustomResults.DataBind();
}

问题是查询本身返回 10 行,因此 gridview 永远不会显示寻呼机。

<asp:GridView ID="GrvCustomResults" runat="server" Visible="false" AutoGenerateColumns="true">
   <PagerSettings  
             Visible="true"  
             Position="TopAndBottom"  
             PreviousPageText="Previous"  
             NextPageText="Next"  
             Mode="NumericFirstLast" />  
   <HeaderStyle CssClass="gridheader" />

4

1 回答 1

3

此代码在 aspx 页面中

<asp:Panel runat="server" id="pnlPager" CssClass="pager">
   </asp:Panel>

这里将在.cs页面中使用的方法这是用于跟踪pagenum和pagesize的记录

      protected int PageNum
        {
            get { return Convert.ToInt16(ViewState["PageNum"]); }
            set { ViewState["PageNum"] = value; }
        }

        protected int PageSize
        {
            get { return Convert.ToInt16(ViewState["PageSize"]); }
            set { ViewState["PageSize"] = value; }
        }


protected int TotalRecord
    {
        get { return Convert.ToInt16(ViewState["TotalRecords"]); }
        set { ViewState["TotalRecords"] = value; }
    }

这是用于调用将发送 pagenum 、页面大小的存储过程的方法

public DataSet GetCollegeSerachData(int PageNum,int PageSize,out int TotalRecords)
        {
            DS = new DataSet();
            ObjDataWrapper = new DataWrapper(ClsCommon.CnnString, CommandType.StoredProcedure);
            TotalRecords=0;
            ErrorCount = 0;
            Searchpattern = "";
            try
            {


                ObjDataWrapper.AddParameter("@PageNum", PageNum);
                ObjDataWrapper.AddParameter("@PageSize", PageSize);

                SqlParameter ObjTotalRecords=(SqlParameter)(ObjDataWrapper.AddParameter("@TotalRowsNum","",SqlDbType.Int,ParameterDirection.Output));



                DS=ObjDataWrapper.ExecuteDataSet("ADMJGetCollegeSearch");
               if(ObjTotalRecords.Value!= DBNull.Value || ObjTotalRecords!=null)
               {
                   TotalRecords=Convert.ToInt32(ObjTotalRecords.Value);
               }

            }
            catch (Exception Ex)
            {
                string err = Ex.Message;
                if (Ex.InnerException != null)
                {
                    err = err + " :: Inner Exception :- " + Ex.InnerException.Message;
                }
                string addInfo = "Error While Executing GetCollegeSerachData in ClsColleges:: -> ";
                ClsExceptionPublisher objPub = new ClsExceptionPublisher();
                objPub.Publish(err, addInfo);
            }
            return DS;
        }

这将返回用于绑定存储过程的数据集

here the store procedure that will used for pagination

GO
/****** Object:  StoredProcedure [dbo].[ADMJGetCollegeSearch]    Script Date: 06/06/2012 15:43:29 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER PROCEDURE [dbo].[ADMJGetCollegeListByState]
@PageNum int,
@PageSize int,
@TotalRowsNum int  output


AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.



    WITH College_CollegeId As
    (
        SELECT 'RowNumber' = ROW_NUMBER() OVER(ORDER BY collegeid asc),College.*
        FROM College

    )


    -- Query result
    SELECT * 
    FROM College_CollegeId
    WHERE RowNumber BETWEEN (@PageNum - 1) * @PageSize + 1 AND @PageNum * @PageSize             
    ORDER BY collegename asc

    -- Returns total records number
    SELECT @TotalRowsNum = count(*) 
    FROM College

END

at last you will bind the the gridview grdCourse.DataSource = DS.Tables[0]; grdCourse.DataBind(); grdCourse.Visible = true;

at the PageIndexChanging(object sender, GridViewPageEventArgs e) of the grid view you will pass the

protected void grdCourse_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
           Pagenum = e.NewPageIndex;

          --call this method public DataSet GetCollegeSerachData(int PageNum,int PageSize,out int TotalRecords)


        }
于 2012-06-06T10:20:57.417 回答