我正在尝试在gridview中实现自定义分页而不使用任何数据源控件。到目前为止,我没有找到任何好的/完整的教程。
以下是我创建gridview的方法:
<asp:GridView ID="GridView1" runat="server" AllowPaging="True" PageSize="10"
onpageindexchanging="GridView1_PageIndexChanging" ShowFooter="True">
</asp:GridView>
单击按钮时会填充此网格。需要根据列表框控件中的项目选择数据库中的行
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);
}
}
}
上面的查询非常慢,因为它带来了所有记录,如何才能获取一个页面记录并仍显示分页?
接下来是gridview PageIndexChanging
事件。当我点击第2页时,它会显示第2页的行,但分页链接会消失。
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);
}
}
}