rchamberlin
rchamberlin

Reputation: 31

Datatable in ASPX Used As DataSource For Multiple User Controls

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.

Upvotes: 0

Views: 1200

Answers (5)

kdmurray
kdmurray

Reputation: 3048

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.

Upvotes: 0

Ravinder Singh
Ravinder Singh

Reputation: 846

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.

Upvotes: 0

IrishChieftain
IrishChieftain

Reputation: 15253

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.

Upvotes: 0

PMC
PMC

Reputation: 4766

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

Upvotes: 1

Canavar
Canavar

Reputation: 48088

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

Upvotes: 1

Related Questions