linq and gridview sorting

D

David

Hi all,

I am using asp.net and c# and linq to sql.

I have...

private void BuildHistory()
{
using (coDataClassesDataContext dc = new coDataClassesDataContext())
{
var TrailerHistory = from th in dc.TrailerHistories.Where(a =>
a.TrailerID == FleetIDEdit.Text)
orderby th.DateOfRepair descending
select th;

HistoryGridView.DataSource = TrailerHistory;
HistoryGridView.DataBind();
}
}

then I want to sort the gridview by clicking a column title, so I have...


protected void HistoryGridView_Sorting(object sender,
GridViewSortEventArgs e)
{

DataTable dataTable = HistoryGridView.DataSource as DataTable;

if (dataTable != null)
{
DataView dataView = new DataView(dataTable);
dataView.Sort = e.SortExpression + " " +
ConvertSortDirectionToSql(e.SortDirection);

HistoryGridView.DataSource = dataView;
HistoryGridView.DataBind();
}
}


The problem is that dataTable is null.

Stepping through, it tells when I hover over the .DataSource

"Cannot access a disposed object.\r\nObject name: 'DataContext accessed
after Dispose.'."

which is sort of obvious, but it doesn't really tell me enough information
that I can fix it.

Should I basically have my whole linq inside the Sorting function? If so,
how do i then build my orderby clause?

Thanks.

--
Best regards,
Dave Colliver.
http://www.AshfieldFOCUS.com
~~
http://www.FOCUSPortals.com - Local franchises available
 
A

Ashish Sheth

I think you can pass the column name and sortDirection as parameter to your
BuildHistory method and dynamically generate the linq statement based on the
parameter values. Something like this:

private void BuildHistory(string columnName, string direction)
{
using (coDataClassesDataContext dc = new coDataClassesDataContext())
{
var TrailerHistory = from th in dc.TrailerHistories.Where(a =>
a.TrailerID == FleetIDEdit.Text)
select th;
if(columnName == "DateOfRepair" && direction == "ascending")
{
TrailerHistory = TrailerHistory.OrderBy(x => x.DateOfRepair)
}
else if(columnName == "DateOfRepair" && direction == "descending")
{
TrailerHistory = TrailerHistory.OrderByDescending(x =>
x.DateOfRepair)
}
HistoryGridView.DataSource = TrailerHistory;
HistoryGridView.DataBind();
}
}
Obviously you have to write if/else statement for each of your column.

regards,
Ashish Sheth
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top