views:

173

answers:

1

I am looking for a way to do paging with a GridView when i set the datasource at run time using a linq query. here is my code:

ETDataContext etdc = new ETDataContext();
var accts = from a in etdc.ACCOUNTs
            orderby  a.account_id
            select new
            {
                Account = a.account_id,
                aType = a.SERVICEs.FirstOrDefault().SERVICE_TYPE.service_type_desc,
                name = a.SERVICEs.FirstOrDefault().service_name,
                Letter_dt = a.create_dt,
                PrimAccthldr = a.PEOPLE.first_name + " " + a.PEOPLE.middle_name + " " + a.PEOPLE.last_name
             };
GridView1.DataSource = accts;
GridView1.BindData();

I have the grid set to allow paging, but I get an error that says that the PageIndexChanging event has not been handled. I searched around and found the following:

protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
     GridView1.PageIndex = e.NewPageIndex;
     GridView1.DataBind();
}

But that works well when you use a datatable but not with linq. If I add a rebind in the event, it has to requery 7000 records which can be a little slow. Does anyone know how to fix the paging when using linq like this?

+1  A: 

A possible solution:

http://www.devtoolshed.com/content/gridview-objectdatasource-linq-paging-and-sorting

http://www.dbtutorials.com/display/linq-to-sql-paging-cs.aspx

Other possibility here:

Use LINQ Data Source as described by Scott Guthrie (the father of ASP) http://weblogs.asp.net/scottgu/archive/2007/07/16/linq-to-sql-part-5-binding-ui-using-the-asp-linqdatasource-control.aspx

Leniel Macaferi
nope not using a DAL or objectdatasource object for this. Just simply creating an anonymous type with linq then binding straight to the grid.
ecspot
If wanna follow this way you'll have poor performance. It's not the proper way of doing this... You should use a LINQ Data Source for example that gives you support for an efficient paging.
Leniel Macaferi
I can't link multiple tables using the linqdatasource otherwise I'd just bind to that. do you know a way to use the linqdatasource to do this query? The data comes from 4 different tables.
ecspot
You definitely can. Read this one: http://weblogs.asp.net/scottgu/archive/2007/09/07/linq-to-sql-part-9-using-a-custom-linq-expression-with-the-lt-asp-linqdatasource-gt-control.aspx. Go to this part: Using the <asp:LinqDataSource> Selecting Event
Leniel Macaferi
using selecting event on linqdatasource to add custom query worked like a charm. Thanks for the help.
ecspot
You're welcome. :P
Leniel Macaferi