点击“下一页”时Request传值丢失
上一篇文章里面,我实现了DataList分页,但是又有一个问题出现了!
问题如下:
我编写了两个页面,第一个页面是Default.aspx,这是一个搜索首页,它上面只有一个供用户输入查询条件的textbox以及一个提交搜索条件的button,点击了这个button以后,就进入第二个页面GoodsDetail.aspx,这个页面返回的是符合用户搜索条件的商品。现在有一个问题,在GoodsDetail.aspx中点击“下一页”时,出现错误: System.NullReferenceException: 未将对象引用设置到对象的实例。
错误的代码如下:
default.aspx.cs
protected void Btn_Search_Click(object sender, EventArgs e) { Response.Redirect("GoodsDetail.aspx?value=" + this.Tbx_Search.Text); }
GoodsDetail.aspx.cs
protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { this.DataList1.DataSource = pds(); this.DataList1.DataBind(); } } private PagedDataSource pds() { string s = Request["value"].ToString(); string strSql = "select GoodsDetail.*,GoodsIndex.ImageURL from GoodsDetail,GoodsIndex where GoodsIndex.GoodsID like'%" + s + "%' and GoodsIndex.GoodsID=GoodsDetail.GoodsID"; DB db = new DB(); DataSet ds = db.GetDataSet(strSql); PagedDataSource pds = new PagedDataSource(); pds.DataSource = ds.Tables["MyTable"].DefaultView; pds.AllowPaging = true;//允许分页 pds.PageSize = 5;//单页显示项数 pds.CurrentPageIndex = Convert.ToInt32(Request.QueryString["page"]); return pds; }
解决办法:改用Session传值
改正后的代码如下:
default.aspx.cs
protected void Btn_Search_Click(object sender, EventArgs e) { Session["value"] = this.Tbx_Search.Text; Response.Redirect("GoodsDetail.aspx?value=" + this.Tbx_Search.Text); }
注意:这里的Session["value"] = this.Tbx_Search.Text一定要放在Response.Redirect之前,否则,在对Session赋值以前就已经页面跳转,那么Session值就为空了!
GoodsDetail.aspx.cs
protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { this.DataList1.DataSource = pds(); this.DataList1.DataBind(); } } private PagedDataSource pds() { string s = Session["value"].ToString(); string strSql = "select GoodsDetail.*,GoodsIndex.ImageURL from GoodsDetail,GoodsIndex where GoodsIndex.GoodsID like'%" + s + "%' and GoodsIndex.GoodsID=GoodsDetail.GoodsID"; DB db = new DB(); DataSet ds = db.GetDataSet(strSql); PagedDataSource pds = new PagedDataSource(); pds.DataSource = ds.Tables["MyTable"].DefaultView; pds.AllowPaging = true;//允许分页 pds.PageSize = 5;//单页显示项数 pds.CurrentPageIndex = Convert.ToInt32(Request.QueryString["page"]); return pds; }