要想实现无刷新分页,就需要拦截GridView的PageIndexChange()事件,然后用ICallBackEventHandler实现无刷新回调.可是我发现如果GridView采用正常的分布方法的话,很难在客户端捕获到这个事件.于是我想了个办法,那就是采用模版的方式来编辑用于分页操作的Row,在模版放上我们自己添加上去的控件来实现翻页操作.具体的做法是:
1.往页面上放一个GridView,将其放置于一个DIV中.正常设置分页操作.
2.进入模版编辑界面,选择编辑Pager Template,放上用于执行分页操作的控件.我的做法是放两个LinkButton控件.ID分别设为lnkbtnPrev,lnkbtnNext.
3.在GridView1_DataBound事件中给这两个控件添加相应的客户端事件.代码如下:
GridViewRow pagerRow = GridView1.BottomPagerRow;
LinkButton lnkPrev = (LinkButton)pagerRow.Cells[0].FindControl("lnkbtnPrev");
LinkButton lnkNext = (LinkButton)pagerRow.Cells[0].FindControl("lnkbtnNext");
int newPageIndex = GridView1.PageIndex;
lnkPrev.Enabled = false;
lnkNext.Enabled = false;
lnkPrev.Attributes.Remove("onclick");
lnkNext.Attributes.Remove("onclick");
if (newPageIndex > 0)
{
lnkPrev.Enabled = true;
lnkPrev.Attributes.Add("onclick", "setPageTo(" + (newPageIndex - 1).ToString() + ");return false;");
}
if (newPageIndex < GridView1.PageCount - 1)
{
lnkNext.Enabled = true;
lnkNext.Attributes.Add("onclick", "setPageTo(" + (newPageIndex + 1).ToString() + ");return false;");
}
4.在客户端脚本中添加setPageTo()方法,以实现回调.
function setPageTo(pageIndex)
{
var context=document.getElementById("listDIV");
context.innerHTML="<IMG SRC='Images/pie.gif' />数据加载中...";
var arg='pageChange|'+pageIndex;
<%= ClientScript.GetCallbackEventReference(this, "arg", "onCallServerComplete", "context")%>;
}
function onCallServerComplete(result,context)
{
context.innerHTML=result;
}
5.在服务器端添加用于实现回调的方法,重新生成GridView分页后的HTML代码,传回客户端.
public void RaiseCallbackEvent(string eventArgument)
{
serverReturn = eventArgument;
}
public string GetCallbackResult()
{
return pageChange(int.Parse(serverReturn ));
}
private string pageChange(string newIndex)
{
int newPageIndex = int.Parse(newIndex);
//设置数据源
GridView1.DataBind();
return getRenderCode();
}
private string getRenderCode()
{
StringWriter writer1 = new StringWriter(CultureInfo.InvariantCulture);
HtmlTextWriter writer2 = new HtmlTextWriter(writer1);
GridView1.Visible = true;
GridView1.RenderControl(writer2);
writer2.Flush();
writer2.Close();
return writer1.ToString();
}
PS:在你的页面中继承System.Web.UI.ICallbackEventHandler接口。//一定要继承这个接口
public partial class _Default : System.Web.UI.Page, System.Web.UI.ICallbackEventHandler
{
protected void Page_Load(object sender, EventArgs e)
{
}
#region ICallbackEventHandler 成员
public string GetCallbackResult()
{
}
public void RaiseCallbackEvent(string eventArgument)
{
}
}