c# – ListView排序不设置SortExpression和SortDirection

我正在研究一个ListView,并且在实现排序时我感觉到我在做一些根本错误的事情.我不是依赖于List1.SortExpression和List1.SortDirection的值,而是依赖于隐藏字段,因为List1.SortExpression总是空白而List1.SortDirection总是SortDirection.Ascending.

在我的.aspx页面上:(编辑出不相关的代码)

<asp:HiddenField runat="server" ID="hdnSortExpression" />
<asp:HiddenField runat="server" ID="hdnSortDirection" />

<asp:ListView runat="server" ID="List1"  
    OnItemCommand="List1_ItemCommand"
    OnSorting="List1_Sorting">
<LayoutTemplate>
    <table border="0" cellpadding="1">
    <thead>
    <tr>
        <th><asp:LinkButton runat="server" ID="BtnCompanyCode" CommandName="Sort" CommandArgument="CompanyCode" Text="Company Code" /></th>
        ... more columns ...
    </tr>
    </thead>

    <tbody>
        <tr runat="server" id="itemPlaceholder"></tr>
    </tbody>
    </table>
</LayoutTemplate>

在我的守则背后:

protected void List1_ItemCommand(object sender, ListViewCommandEventArgs e)
{
    // empty for now
}

protected void List1_Sorting(object sender, ListViewSortEventArgs e)
{
    SortDirection sortDirection;
    String sortExpression = e.SortExpression;   // how we need to do it in Sorting

    if (hdnSortExpression.Value.ToLower() == sortExpression.ToLower())
        sortDirection = hdnSortDirection.Value == SortDirection.Ascending.ToString() ? SortDirection.Descending : SortDirection.Ascending;
    else
        sortDirection = SortDirection.Ascending;

    DoSortList(sortExpression, sortDirection);  // this sets column headings' sort indicator arrows
    List1_BindData(sortExpression, sortDirection);  // sets DataSource and calls DataBind()

    // the hacky part: setting hidden fields to store sortExpression and sortDirection
    hdnEligibilitySortExpression.Value = sortExpression;
    hdnEligibilitySortDirection.Value = sortDirection.ToString();
}

private void List1_BindData(String sortExpression, SortDirection sortDirection)
{
    List<SomeEntity> list = null;

    list = SomeEntity.GetBySsn(_ssn).ToList();  // methods generated by an ORM pointing to an Oracle database

    switch (sortExpression.ToLower())
    {
        case "CompanyCode":
        if (sortDirection == SortDirection.Ascending)
            List1.DataSource = list.OrderBy(o => o.CompanyCode);
        else
            List1.DataSource = list.OrderByDescending(o => o.CompanyCode);
        break;

        ... other cases ...
    }

    List1.DataBind();
}

它工作正常 – 每列都正确排序,单击相同的列反转排序方向,但我必须得出结论,我已经错误地连接了因为我不能依赖于SortDirection和SortExpression属性.我究竟做错了什么?

最佳答案 看看这个
MSDN example.

您会注意到DataSource是一个SqlDataSource.这是.Net了解如何排序的DataSource类型之一.其他人,不是那么多.

这是指定DataSource类型的另一个MSDN article

The data source controls that provide built-in support for sorting are the LinqDataSource, ObjectDataSource, SqlDataSource, and AccessDataSource controls.

点赞