开发者

how to retain the value of global string variable even after page load in asp.net

I am having problems in retaining the string variable which I defined on the top of my scoop, everytime when page loads the string value becomes null. below is the snippet of the code:

public partial class Caravan_For_Sale : Syste开发者_如何转开发m.Web.UI.Page
{
string check;
PagedDataSource pds = new PagedDataSource(); //paging

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {

        BindGrid();
    } 

}

private void BindGrid()
{
    DataTable dt = null;
    switch (check)
    {
        case "0-1500":
            break;
        case "1500-2000":
            dt = caravans.GetFilterbyPrice1();
            break;

        case "2000+":

            break;

        default:
             dt = caravans.GetAllCaravans();
            break;
    }
   // DataTable dt = caravans.GetAllCaravans();

    pds.DataSource = dt.DefaultView;
    pds.AllowPaging = true;
    pds.PageSize = 3;//add the page index when item exceeds 12 //Convert.ToInt16(ddlPageSize.SelectedValue);
    pds.CurrentPageIndex = CurrentPage;
    DataList1.RepeatColumns = 3; // 4 items per line
    DataList1.RepeatDirection = RepeatDirection.Horizontal;

    DataList1.DataSource = pds;
    DataList1.DataBind();

    lnkbtnNext.Enabled = !pds.IsLastPage;
    lnkbtnPrevious.Enabled = !pds.IsFirstPage;

    doPaging();

}
  protected void lnkPrice2_Click(object sender, EventArgs e)
{
    LinkButton _sender = (LinkButton)sender;
    check = _sender.CommandArgument;
 //  items["test"] = test;
    DataTable dt = caravans.GetFilterbyPrice2();
    if (dt.Rows.Count < 3)
    {
        lnkbtnNext.Enabled = false;
        lnkbtnPrevious.Enabled = false;

    }

    CurrentPage = 0;
    BindGrid();

}

   protected void dlPaging_ItemCommand(object source, DataListCommandEventArgs e)
{
    if (e.CommandName.Equals("lnkbtnPaging"))
    {

        CurrentPage = Convert.ToInt16(e.CommandArgument.ToString());
        BindGrid();
    }
}

The string check becomes null everytime when the dlPaging_ItemCommand becomes active(page loads). Any help or suggestions will be appreciated


As far as I know, you have two options:

1) Load it again.
Not sure if it's possible in your case. This is usually done when dealing with database queries.

2) Put it in the ViewState just like this:

ViewState["check"] = check;

And load it after with this:

string check = Convert.ToString(ViewState["check"]);


Your class is instantiated on every load so it will not have a global variable from page view to page view. You will need to store it somehow. Like in the querystring or a session. You can also use the viewstate.

For example

ViewState("Variable") = "Your string"


Viewstate is the way to go, as the other people have answered. Whatever you do, please don't stuff it in the session.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜