1

I am trying to implement custom pagination in gridview without using any data source controls. I didn't find any good/complete tutorial so far.

Here is how I am creating the gridview:

 <asp:GridView ID="GridView1" runat="server" AllowPaging="True" PageSize="10" 
               onpageindexchanging="GridView1_PageIndexChanging" ShowFooter="True">
 </asp:GridView>

This grid is populated when a button is clicked. Rows from the database need to be picked based on items in listbox control

protected void btnSearch_Click(object sender, EventArgs e)
{
    using (context = new TrackForceDataEntities())
    {
        try
        {
            string[] arr = lstStates.Items.Cast<ListItem>().Select(i => i.Text).ToArray();
            var searchResults = context.data_vault.Where(d => arr.Contains(d.STATE)).OrderByDescending(d=>d.STATE);

            GridView1.DataSource = searchResults;
            GridView1.DataBind();
         }
         catch (Exception exception)
         {
             Response.Write(exception.Message);
         }
     }
}

This above query is very slow because it is bringing all records, How can I fetch only one page records and still show paging ?

Next is the gridview PageIndexChanging event. When I click page 2, it shows page 2 rows but paging links disappear.

protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
    using (context = new TrackForceDataEntities())
    {
        try
        {
            // var searchResults = context.data_vault.Where(d => d.STATE == lstStates.SelectedItem.Text).OrderBy(d => d.dv_id).Take(10).Skip(2);


            //var selection = lstStates.Items(i => i.Text).ToArray();
            //var result = context.data_vault.Where(x => selection.Contains(x.Prop));

            string[] arr = lstStates.Items.Cast<ListItem>().Select(i => i.Text).ToArray();

            var result = context.data_vault.Where(d => arr.Contains(d.STATE)).OrderByDescending(d => d.STATE).Skip(e.NewPageIndex * GridView1.PageSize)
                                         .Take(GridView1.PageSize)
                .ToList();

            //var result = context.data_vault.Where(d => d.STATE == lstStates.SelectedItem.Text).OrderBy(d => d.STATE).Skip(e.NewPageIndex * GridView1.PageSize).Take(GridView1.PageSize).ToList();
            //// this is very important part too
            GridView1.PageIndex = e.NewPageIndex;

            GridView1.DataSource = result;
            GridView1.DataBind();

        }
        catch (Exception exception)
        {
            Response.Write(exception.Message);
        }
    }
}
4

1 回答 1

0

通过以下链接您将能够得到答案。分页是通过 sql server 通过传递页码和页面大小来完成的。

点击这里

于 2012-06-09T07:31:58.433 回答