点击“下一页”时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;
        }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值