0
votes

What I have now is code for setting ViewState or Session of desired variable:

 if (ViewState["currentPage"] != null)
        {
            currentPage = Convert.ToInt32(ViewState["currentPage"].ToString());
        }
        else
        {
            currentPage = 0;
            ViewState["currentPage"] = currentPage.ToString();
        }

currentPage field is global with default value of zero in CodeBehind (public int currentPage = 0;) and therefore its initial value is zero whenever the page is loaded. So I wrote these few lines to save its last value. Just to mention that wherever currentPage value is changed in CodeBehind, I added "ViewState["currentPage"] = currentPage.ToString();" in line after.

What I want is universal function that takes two arguments, variable and value, for setting ViewState according to code above. So if necessary, I can just call method, something like that: setViewState(currentPage, 0)

2

2 Answers

0
votes

is there a need for you to have the variable as an input parameter - what is wrong with simple creating a function in a class somewhere in your application and passing the value in then returning the created value ? i.e.

public int setViewState(int value) {
  //return and set value here?
}

so would be used like currentValue= setViewState(50);

0
votes

I think the difficulty you are going to have with a global function is that ViewState is local to the page.

A couple of things that might help you though:

  1. Don't forget ViewState is an object so you don't have to do the ToString
  2. You could put the necessary code in a Property like this:

    public int? TestInt {
        get { return ViewState["TestInt"] as int?; }
        set { ViewState["TestInt"] = value; }
    }
    

I like this approach because its very obvious what the code is doing, particuarly as I try to minimize ViewState usage where possible.