C# 如何在与列表绑定时对网格视图数据进行排序

C# 如何在与列表绑定时对网格视图数据进行排序,c#,asp.net,C#,Asp.net,我正在将ASP.Net网格视图与列表对象绑定。我创建了Country和City类,这些类继承自它们各自的接口 public interface ICountry { int cmID { get; set; } string cmName { get; set; } } public interface ICity { int ctyId { get; set; } string ctyName { get; set; } } pub

我正在将ASP.Net网格视图与列表对象绑定。我创建了Country和City类,这些类继承自它们各自的接口

public interface ICountry
{
    int cmID { get; set; }
    string cmName { get; set; }        
}

public interface ICity 
{
    int ctyId { get; set; }
    string ctyName { get; set; }    
}

public class Country : ICountry
{
    public int cmID { get; set; }
    public string cmName { get; set; }     
}

 public class City : ICity
{
    public int ctyId { get; set; }
    public string ctyName { get; set; }
    public ICountry Country { get; set; }   


public List<City> GetAllCity(string SortDirection, string SortExpression)
{
   DataTable dt = FillCity()            //returns city,country in a table
   List<City> obj = new List<City>();          
   foreach(DataRow dr in dt.Rows)
   {
       City o = new City();
       o.ctyName = dr["ctyName"].ToString();
       o.Country.cmName = dr["cmName"].ToString();
       obj.Add(o);
   }

       dt.Dispose();
       return obj;          
}


    <asp:GridView ID="GridView1" runat="server" Width="100%" AutoGenerateColumns="false" PageSize="15"
AllowPaging="true" OnPageIndexChanging="GRV1_PageIndexChanging"
AllowSorting="true" onsorting="GRV1_Sorting">                                    
<Columns>
    <asp:TemplateField ItemStyle-Width="10%" ItemStyle-HorizontalAlign="Left" HeaderText="City" SortExpression="ctyName ">
        <ItemTemplate>
            <%# Eval("ctyName")%>
        </ItemTemplate>
    </asp:TemplateField>
    <asp:TemplateField ItemStyle-Width="15%" ItemStyle-HorizontalAlign="Left" HeaderText="Country" SortExpression="Country.cmName">
        <ItemTemplate>
            <%# Eval("Country.cmName")%>
        </ItemTemplate>
    </asp:TemplateField>
</Columns></asp:GridView>
我曾尝试使用Linq进行排序,但失败了。如何使用列表对网格视图中的数据进行排序

我试过使用下面的方法,但没有效果

            if (obj != null)
        {

            var param = Expression.Parameter(typeof(MemorandaClosing), SortExpression);
            var sortExpression = Expression.Lambda<Func<MemorandaClosing, object>>(Expression.Convert(Expression.Property(param, SortExpression), typeof(object)), param);

            if (SortDirection == "ASC")
            {
                obj.AsQueryable<MemorandaClosing>().OrderBy(sortExpression);
            }
            else
            {
                obj.AsQueryable<MemorandaClosing>().OrderByDescending(sortExpression);
            };
        }
在GetAllCity中尝试这样的方法

这将按CityName订购

return obj.OrderBy(x => x.ctyName).ToList();  

除了@Ganesh_Devlekar所说的,您也可以使用以下方法进行排序:

return obj.OrderByDescending(x => x.ctyName).ToList()
甚至用Where或其他东西做一些过滤


我希望这有助于

如果您想在可能的两个不同字段上排序,您将需要更复杂的内容。具体地说,您需要为GetAllCity方法指定要排序的字段。这里有一种可能的方法,当然不是最优雅的:

public List<City> GetAllCity(bool SortOnCity, bool SortOnCountry)
{
    //main code omitted for brevity

    if (SortOnCity && !SortOnCountry)
        return obj.OrderBy(x => x.ctyName).ToList();
    else if (SortOnCountry && !SortOnCity)
        return obj.OrderBy(x => x.Country.cmName).ToList();
    else if (SortOnCity && SortOnCountry)
        return obj.OrderBy(x => new {x.ctyName, x.Country.cmName}).ToList();
}
然后,将传入一个lambda表达式,该表达式表示要排序的属性,类似于:

GetAllCity(SortDirection.Ascending, c => new {c.ctyName, c.Country.cmName});

请注意,这只是一个示例,可能需要根据您的具体情况进行调整。

必须手动进行排序。根据你的要求,它可能会很复杂——比如说,如果你想要一个三级排序。假设您希望参照单个字段对数据进行排序。您需要执行以下操作:

public List<City> GetAllCity<TKey>(SortDirection order, Expression<Func<City, TKey>> SortExpression)
{
    //main code omitted for brevity

    if (order == SortDirection.Ascending)
        return obj.OrderBy(SortExpression);
    else
        return obj.OrderByDescending(SortExpression);

}
跟踪ViewState中的排序方向 处理GridView的排序事件,并从后端适当地查询数据。 以下是改编自以下内容的示例片段:


感谢各位为我的问题提供解决方案的提示。在这里,我发现了stackoverflow中的post,它在我的例子中非常有效


这是什么?它指的是什么对象实例?好的,我的错。这是一个城市对象实例…但是为什么要一次又一次地将同一个实例添加到ListOk,发布编辑,现在它有了意义。如果我必须将排序表达式和排序方向传递给GetAllCity方法,该怎么办。比如说,如果我需要使用国家名称进行排序怎么办?如果条件永远无法运行,您的最后一个条件是绝对正确的,先生-我会更正它。谢谢:现在看起来还可以,但我更愿意写if SortOnCity&&SortOnCountry{}else if SortOnCity{}else if SortOnCountry{}我永远不会写这样的生产代码-这纯粹是为了演示这个概念。@Katstevens谢谢你的建议。您能否演示如何使用传递给OrderBy方法的lambda expression参数。
public SortDirection GridViewSortDirection
{
    get
    {
        if (ViewState["sortDirection"] == null)
            ViewState["sortDirection"] = SortDirection.Ascending;

        return (SortDirection)ViewState["sortDirection"];
    }
    set { ViewState["sortDirection"] = value; }
}

protected void gridView_Sorting(object sender, GridViewSortEventArgs e)
{           
    if (GridViewSortDirection == SortDirection.Ascending)
    {
        myGridView.DataSource = GetData(e.SortExpression, SortDirection.Ascending);
        GridViewSortDirection = SortDirection.Descending;
    }
    else
    {
        myGridView.DataSource = GetData(e.SortExpression, SortDirection.Descending);
        GridViewSortDirection = SortDirection.Ascending;
    };
    myGridView.DataBind();        
}