我有一个数据库驱动的gridview启用分页.所有工作正常,并在page_load上绑定如下:
sqldataadapter da = new saldatadapter("sql query"),con); datatable dt = new datatable(); gridview1.datasource = dt; gridview1.databind();
有没有一个选项,我可以启用页码自动出现在url?我想这样做的原因是,我可以通过网页电子邮件发送网址,然后当用户点击网址时,它会导致gridview从正确的页面显示数据.
更新2 – 当前要求的完整代码:
public partial class conflict_search_Default : System.Web.UI.Page { protected void Page_Load(object sender,EventArgs e) { if (!Page.IsPostBack) { if (Request.QueryString["page"] != null) { int index = int.Parse(Request.QueryString["page"]); GridView1.PageIndex = index; BindData(); } else { BindData(); } } else { BindData(); } } private void BindData() { sqlConnection con = new sqlConnection(ConfigurationManager.AppSettings["connString"]); sqlDataAdapter da = new sqlDataAdapter("sql query here which returns over 100 pages",con); DataTable dt = new DataTable(); da.Fill(dt); GridView1.DataSource = dt; GridView1.DataBind(); } protected void GridView1_PageIndexChanging(object sender,GridViewPageEventArgs e) { int index = e.NewPageIndex + 1; string url = HttpContext.Current.Request.Url.AbsoluteUri; e.Cancel = true; Response.Redirect(string.Format("{0}?page={1}",url,index)); } protected void GridView1_PageIndexChanged(object sender,EventArgs e) { BindData(); } }
当我尝试点击数据网格底部的分页号时,这会给我一个错误.错误如下:
如果我加载页面新鲜,它将加载.如果我点击页面5,它会在url中显示?page = 5,这是我期望的,但是由于某些原因,第6页在屏幕底部的分页号码上被选中.如果我然后点击第10页,例如,url更改为?page = 5?page = 10,这显然是错误的,这给出错误:
Input string was not in a correct format. int index = int.Parse(Request.QueryString["page"]);
解决方法
如果您更改功能GridView1_PageIndexChanging中的代码如下所示将会工作:
protected void GridView1_PageIndexChanging(object sender,GridViewPageEventArgs e) { e.Cancel = true; int index = e.NewPageIndex; string urlPath = HttpContext.Current.Request.Url.AbsoluteUri; Uri uri = new Uri(urlPath); string url = uri.GetLeftPart(UriPartial.Path); Response.Redirect(string.Format("{0}?page={1}",index)); }
此外,您不需要处理GridView1_PageIndexChanged事件.