Harshit
Harshit

Reputation: 159

how to access page load methods in other methods of a same class in asp.net

I have a method in page load:

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        IEnumerable<int> Ids = GetIds();

    }
}
public IEnumerable<int> GetIds()
{
    IEnumerable<int> Ids;
    using ()
    {
        //query to get data from back end
    }
    return Ids;
}

how can i use page load Ids List in other method of a same class?is it possible?

actually i am trying to load all the data of back end at once on page load and then use them in different methods of a same class.

Upvotes: 1

Views: 1078

Answers (2)

Mateus Schneiders
Mateus Schneiders

Reputation: 4903

If you simply use a variable to store the IDs value, it will not be persisted and will be null in the next postback.

You can persist data across postbacks using ViewState, for example:

private List<int> IDs
{
    get{ return (List<int>)ViewState["IDs"]; }
    set{ ViewState["IDs"] = value; }
}

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        IDs = GetIds();
        //IDs will be available in the next postbacks
    }
}

Upvotes: 1

Zaheer Ul Hassan
Zaheer Ul Hassan

Reputation: 781

Declare it as global variable in class.

IEnumerable<int> Ids;
protected void Page_Load(object sender, EventArgs e)
        {

            if (!IsPostBack)
            {
                 Ids = GetIds();

             }
    }
 public IEnumerable<int> GetIds()
   {
        IEnumerable<int> IdsToReturn;
        using ()
        {
               //Here you can get Ids;  
               //query to get data from back end
        }
        return IdsToReturn;
    }

Upvotes: 2

Related Questions