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);
}
}
}