views:

775

answers:

1

hey guys

I'm in a bit of pickle here.

up till now I have a linq query that fills a datagrid perfectly with filterconditions. however, when I try to implement sorting I fail.

I have the following code behind. it catches the start of the sort.

protected void gvServers_Sorting(object sender, GridViewSortEventArgs e)
{
    if (e.SortDirection == SortDirection.Ascending)
    {
        SortDataAsc(e.SortExpression);
    }
    else if (e.SortDirection == SortDirection.Descending)
    {
        SortDataDesc(e.SortExpression);
    }
}

in these submethods I'd want to hendle the sorting of each possible sorting expression. however, when I try to use the data that is already in the gridview it won't allow me to linq it with an orderby

private void SortDataAsc(string p)
{
    var data = gvServers.DataSource;
    switch (p)
    {
        case "domain":
            var sorted = data.nothinghappenshere
        default:
            break;
    }
}

as you can see pointing to the nothinghappenshere I cannot sort the data (proabaly because it's a var).

What I've read online is that you can just get the data from the gridview as I try to do in SortDataAsc(), but it doesn't seem to work that way.

I simply want to order by a certain field in my resultset (which is in this case an anonymous class derived from a join)

does anyone have a solution for this issue?

thx,

J.

+1  A: 

Well, it's because DataSource is weakly typed.

If you cast it to IEnumerable<YourDataType> it should be fine. However, note that OrderBy and OrderByDescending don't sort in place - you'd have to order the data and then reassign the DataSource.

You say that your data type as an anonymous type - you'll have to change that, I'm afraid. Anonymous types can only (easily) be used in a strongly typed way in single method - you can't specify the name later on, so you can't refer to the same properties etc.

It's not terribly hard to convert an anonymous type into a named one though. Here's an answer giving an example.

Jon Skeet
as I mentioned above, there is no datatype to type it with. the results are a join in which I used the select new {} to get everything I need ...
Jan W.
Sorry, was busy editing. Will try to find the anonymous type question.
Jon Skeet
I was thinking about that too, but at the time it seemd overkill to make a type for that purpose.I suppose it's the only way out to be able to sort ...
Jan W.
It's the only way to sort without using reflection of some kind, yes. (Well, there *are* grotty hack ways to effectively reuse an anonymous type, but they're horrible and I wouldn't recommend them.)
Jon Skeet
the link you gave me suggests I make a default constructor with all properties, I would thinnk this isn't necesarry when using object initializers ...
Jan W.
If you don't mind it being mutable, that would work. That answer was meant to be creating a directly equivalent type, that's all.
Jon Skeet