ASP.net GridView排序与LINQ结果 [英] ASP.net gridview sorting with linq result

查看:116
本文介绍了ASP.net GridView排序与LINQ结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

到目前为止,我有一个linq查询,它用filterconditions完美地填充了一个数据网格. 但是,当我尝试实施排序时会失败.

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

在这些子方法中,我想了解每个可能的排序表达式的排序. 但是,当我尝试使用gridview中已经存在的数据时,将不允许我使用orderby来对数据进行限制

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).

我在网上阅读的内容是,您可以像我在SortDataAsc()中尝试的那样,仅从gridview中获取数据,但这种方式似乎不起作用.

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)

推荐答案

好吧,这是因为DataSource是弱类型的.

Well, it's because DataSource is weakly typed.

如果将其强制转换为IEnumerable<YourDataType>,应该没问题.但是,请注意,OrderByOrderByDescending的排序不正确-您必须对数据进行排序,然后重新分配DataSource.

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.

这篇关于ASP.net GridView排序与LINQ结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆