Reputation: 52027
I have a gridview that I bind with the result of a linq query that's in a list. In my code behind, I then bind the gridview with the list
MyGrid.DataSource = MyList;
MyGrid.DataBind();
I also have the grid with sorting enabled:
<asp:GridView ID="MyGrid" AllowSorting="True" OnSorting="SortMyGrid">
In the code behind, I have the event handler set up like this:
protected void MyGrid(object sender, GridViewSortEventArgs e)
{
var NewDataSource = from d in MyList
orderby e.SortExpression
select d;
}
Now the problem is that MyList is null when the event handler takes over! I'm tracing it and I see it loaded fine, I see the gridview on the page with the correct data but as soon as I click a column header to sort the grid, the MyList goes to null! Why?? What's causing the problem?
Upvotes: 2
Views: 4807
Reputation: 13947
Once your data is bound, the source is effectively "lost" on the next event. If you need to retain it, you can put it in your session and pull it out when you need it.
EDIT Well, the term 'lost' sounds harsh, but it is no longer referenced. Wherever you have a reference to it (page load, most likely), you can do this:
MyGrid.DataSource = MyList;
MyGrid.DataBind();
Session["MyList"] = MyList;
Then, in your event handler (when you need it again), pull it back out:
List<MyObjectType> MyList = Session["MyList"] as List<MyObjectType>;
where List<MyObjectType>
is the type of your list. The Session
is basically a Dictionary, which is why you can store anything in it, but you have to cast it on the way out.
Upvotes: 5
Reputation: 1065
protected void MyGrid(object sender, GridViewSortEventArgs e)
{
var NewDataSource = from d in MyList
orderby e.SortExpression
select d;
MyGrid.DataSource = NewDataSource;
MyGrid.DataBind();
}
Upvotes: 1