Search code examples
c#asp.netlinqdatasource

Prevent LinqDataSource selecting on every post-back


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?


Solution

  • 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();
    }