GridView行定位问题
Default.aspx 页代码:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="GridView分页导航.aspx.cs" Inherits="GridView分页导航" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>无标题页</title> </head> <body> <form id="form1" runat="server"> <div> <asp:GridView ID="GridView1" runat="server" Font-Size="12px" CellPadding="3" OnRowDataBound="GridView1_RowDataBound"> <HeaderStyle BackColor="AliceBlue" /> </asp:GridView> <asp:Literal ID="pager" runat="server"></asp:Literal> </div> </form> </body> </html>Default.aspx.cs 页代码:
int page = 0;//定义当前页码 protected void Page_Load(object sender, EventArgs e) { page = Convert.ToInt32(Request.QueryString["page"]); //获取当前页的页码并进行安全转换 if (page < 1) page = 1; GridView1.DataSource = GetRecords(page, 30); GridView1.DataBind(); } public System.Data.DataTable GetRecords(int currentPage, int pageIndex) { string sql = "Data Source=.;Initial Catalog=CA2007Nianjian;User ID=sa;Password=123"; System.Data.SqlClient.SqlConnection cn = new System.Data.SqlClient.SqlConnection(sql); System.Data.SqlClient.SqlDataAdapter da = new System.Data.SqlClient.SqlDataAdapter("select* from QDCAJG", cn); System.Data.DataSet ds = new System.Data.DataSet(); //以上数据库连接随便写,根据需要修改 //下面填充 DataSet 以便进行分页计算 da.Fill(ds, "TableA"); int allRecord = ds.Tables["TableA"].Rows.Count; int totalPage = 0; if (allRecord % pageIndex == 0) { totalPage = allRecord / pageIndex; } else { totalPage = allRecord / pageIndex + 1; } if (currentPage > totalPage) { currentPage = totalPage; } int startRecords = (currentPage - 1) * pageIndex; da.Fill(ds, startRecords, pageIndex, "TableB"); //生成导航: string paging = "<a href='Default.aspx?page=1'>首页</a> "; paging += "<a href='Default.aspx?page=" + (currentPage - 1) + "'>上一页</a> "; paging += "<a href='Default.aspx?page=" + (currentPage + 1) + "'>下一页</a> "; paging += "<a href='Default.aspx?page=" + totalPage.ToString() + "'>末页</a>"; pager.Text = paging; return ds.Tables["TableB"]; } protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { //添加导航用的锚点 e.Row.Cells[0].Text += "<a name='a" + e.Row.DataItemIndex.ToString() + "'></a>"; e.Row.Attributes.Add("onclick", "window.location.href='b.aspx?page=" + page.ToString() + "&pos=" + e.Row.DataItemIndex.ToString() + "'"); } }