2

There are a GridView and a LinqDataSource in a page and few buttons which their actions are not related to the GridView and its LinqDataSource. Why on each post-back of those buttons the Selecting method of the LinqDataSource will call? Is this normal?! These unwanted db calls from the LinqDataSource are not required.

Is there any better way?

Babak
  • 3,716
  • 6
  • 39
  • 56

2 Answers2

4

You need to detach the GridView from the data source. I assume you have attached the data source like this, in which case, don't do it this way.

<asp:LinqDataSource 
    runat="server"
    ContextTypeName="AdventureWorksDataContext" 
    TableName="Contacts" 
    ID="LinqDataSource1">
</asp:LinqDataSource>

<asp:GridView 
    ID="GridView1" 
    runat="server"
    DataSourceID="LinqDataSource1" >
</asp:GridView>

Your better off attaching the data source in your code behind when it's needed.

if (dataSourceNeeded == true) {
  GridView1.DataSource = GetDataSource();
  GridView1.DataBind();
}
Razor
  • 17,271
  • 25
  • 91
  • 138
  • Yeah, I was wondering around that point and you bopped me upside the head and pointed me proper. – Merritt Mar 16 '12 at 00:00
  • Unfortunately, apparently my select associated with the LinqDataSource is getting called 2x when I hook it up in this method using a RadGrid and exporting the data... crazy world. – Merritt Mar 16 '12 at 00:04
  • Should the datasource control be wise enough to see that no parameters changed between the postbacks and thus not call the database again? I thought this is how it worked? – julealgon Nov 27 '13 at 19:06
  • You're forgetting that the web is stateless. After the page is sent to the client that data is gone on the server. A postback is a new request and you'll need to ask your database for it again so you can serve up a response to the client. – Razor Dec 06 '13 at 00:51
2

it because grid need to populated on every page load, you may cache datasorce to some variable and store it on the server side (not in viewstate)

Alexander
  • 1,287
  • 1
  • 15
  • 34