tags:

views:

331

answers:

2

in asp.net suggest me a best way for storing and binding datatable to grid to avoid rebinding on each pageload

thanks

A: 

Grid values will be stored in ViewState automatically. You shouldn't need to be rebinding on every postback unless you're changing the data.

If you have a dataset that you're retrieving different "views" from each time, like custom paging or sorting, then you should evaluate using the Cache to store your dataset.

womp
Yep. If you hook into the DataBind event, you'll notice that it does not fire on post back with ViewState enabled unless an action that would invalidate the cached values happens. The GridView is typically fairly smart about knowing when something that would make the cached copy invalid happens. Particularly when used with official data sources, like ObjectDataSource and friends.
Yadyn
A: 

If viewstate is enable then you do not need to rebind.

If something is changing and you need to rebind you have a couple of options. Store your datasource in the viewstate or session. Then you don't need to hit the database each time you need to add a filter or paginate etc.

Eg.

// Load up date initially
public void LoadYourData()
{
    // This gets your data however you are doing it, in this example I am returning
    // a list of objects.
    List<YourObjects> yourData = GetYourData();

    // You then have the option to save it in the session or viewstate, I will
    // demonstrate both.  Make sure if you are using viewstate that your objects are
    // serializable.  You should probably also create helper classes to deal with
    // getting and setting data from the ViewState object or Session.
    Session["YourData"] = yourData;
    ViewState["YourData"] = yourData;
}

// Then make a bind function that gets the data out of whatever store you have it in
public void BindYourGrid()
{
    // I will assume you used session
    grdYourGrid.DataSource = (List<YourObjects>)(Session["YourData"]);
    grdYourGrid.DataBind();
}

So when you need to use it in your Page_Load you could just use the following:

GetYourData();
BindYourGrid();

If you need to apply something a filter you just need to pull the data out of your store (session or viewstate) and perform your manipulation and store it again. Then just call BindYourGrid();.

This way you are never actually hitting the DB unless you need to. There are other methods for caching your datasource's data as well and they all have pros and cons. Go with whatever works in your case though as I have only shown two methods.

Kelsey