views:

136

answers:

5

In an ASPX page, I have 7 user controls loaded. In each user control there are data bound controls (gridview for example).

Currently each user control runs a query to return data. The data returned is the same for each user control, and I filter out what I need to show for each user control. So the same query is being run 7 times (Yeah I know).

What I'd like to do is have the datatable created in the ASPX page, and then allow each gridview use that datatable as its DataSource so the query is only run once.

I'd appreciate any help with this.

+1  A: 

Maybe you can expose a property at your usercontrols that gets the datatable. At your page that includes the user controls, sets the property.

Canavar
+1  A: 

You could set a public property on each control (for example a List) and run the query in the aspx page and pass it to the controls

Paul McCowat
A: 

Seven GridViews is overkill and will seriously hamper the performance of the page. Grab the data once in your main page. You can then set properties on the user controls and display in table format in each user control.

IrishChieftain
A: 

I think the approach you are thinking about will cause you do much extra work. Better you cache the datatable and then before each user control executes the query, you check the cache first. In case you get the datatable from the cache you can use that for performing actions. Else you execute the query and get the datatable from database. That way the existing thing will work and you will get the desired result with minimal effort.

Bootcamp
A: 

If your user controls expose a property that will allow the DataTable to be assigned to it you should be able to provide the functionality by only running the query once:

// In your ASPX page
DataTable dt = new DataTable()
... // populate the table from the database

userControl1.Source = dt;
userControl2.Source = dt;
...
userControl7.Source = dt;

// In your user controls
// Assumes a GridView called myGridView
public DataTable Source
{
    set
    {
        myGridView.DataSource = value;  //or hold it somewhere else
    }
}

It's not the most efficient code of all time, but this way you'll only execute the query one time.

kdmurray