日期:2014-05-18  浏览次数:20449 次

做分页时连接数据库
protected void DataListDaTabind()
  {
  SqlDataSource ads = new SqlDataSource();
  string connectionString = "Data Source=WIN-SD9377RP59L\\SQL2005;Initial Catalog=WebBookShop;User ID=sa;password=ymrs340323";
  SqlConnection conn = new SqlConnection(connectionString);
  conn.Open();
  ads.SelectCommand = "select * from Product order by productid ASC";
  DataView dv = (DataView)ads.Select(DataSourceSelectArguments.Empty);
  PagedDataSource objPage = new PagedDataSource();
  objPage.DataSource = dv;
  objPage.AllowPaging = true;
  objPage.PageSize = 6;
  int TolPage;
  TolPage = objPage.PageCount;
  int CurPage;
  if (Request.QueryString["Page"] != null)
  {
  CurPage = Convert.ToInt32(Request.QueryString["Page"]);
  }
  else
  {
  CurPage = 1;
  }
  objPage.CurrentPageIndex = CurPage - 1;
  lblCurPage.Text = "目前在第" + CurPage.ToString() + "页,共" + TolPage.ToString() + "页";
  lnkFirst.NavigateUrl = Request.CurrentExecutionFilePath + "?Page=1";
  lnkLast.NavigateUrl = Request.CurrentExecutionFilePath + "?Page=" + TolPage.ToString();
  if (!objPage.IsFirstPage)
  {
  lnkPrev.NavigateUrl = Request.CurrentExecutionFilePath + "?Page=" + Convert.ToString(CurPage - 1);
  }
  else
  {
  lnkPrev.Visible = false;
  lnkFirst.Visible = false;
  }
  if (!objPage.IsLastPage)
  {
  lnkNext.NavigateUrl = Request.CurrentExecutionFilePath + "?Page=" + Convert.ToString(CurPage - 1);
  }
  else
  {
  lnkNext.Visible = false;
  lnkLast.Visible = false;
  }
  DataList1.DataSource = objPage;
  DataList1.DataBind();
  }
提示错误ConnectionString 属性尚未初始化

------解决方案--------------------
用数据源控件怎么还用SqlConnection,
这3句
 string connectionString = "Data Source=WIN-SD9377RP59L\\SQL2005;Initial Catalog=WebBookShop;User ID=sa;password=ymrs340323";
SqlConnection conn = new SqlConnection(connectionString);
conn.Open();
改为ads.ConnectionString="Data Source=WIN-SD9377RP59L\\SQL2005;Initial Catalog=WebBookShop;User ID=sa;password=ymrs340323";
------解决方案--------------------
探讨

可以了谢谢,可是为什么在点击下一页时出现错误 “索引 -6 不是为负数,就是大于行数”。怎么办?

------解决方案--------------------

你看看别人的demo分页吧
http://www.webdiyer.com/Controls/AspNetPager