2011-10-05 123 views
4

我有一個簡單的gridview控件綁定到一個sql數據源。現在我啓用了排序功能,但是當我單擊要排序的列時,它會先按升序排序。當我再次單擊同一列時,它按降序對其進行排序。我想切換。我希望它在第一次點擊時降序排列,然後升序第二次。我怎麼做?ASP.NET GridView默認排序順序

這裏是我的GridView控件代碼:

<asp:GridView ID="GridView1" runat="server" AllowSorting="True" 
     AutoGenerateColumns="False" BackColor="White" BorderColor="#999999" 
     BorderStyle="Solid" BorderWidth="1px" CellPadding="3" 
     DataSourceID="SqlDataSource1" ForeColor="Black" GridLines="Vertical" > 
     <AlternatingRowStyle BackColor="#CCCCCC" /> 
     <Columns> 
      <asp:BoundField DataField="Name" HeaderText="Name" /> 
      <asp:BoundField DataField="Team" HeaderText="Team" SortExpression="Team" /> 
      <asp:BoundField DataField="Matches" HeaderText="Matches" 
       SortExpression="Matches" /> 
      <asp:BoundField DataField="Points" HeaderText="Points" 
       SortExpression="Points" /> 
      <asp:BoundField DataField="Tries" HeaderText="Tries" SortExpression="Tries" /> 
      <asp:BoundField DataField="Conversions" HeaderText="Conversions" 
       SortExpression="Conversions" /> 
      <asp:BoundField DataField="Penalties" HeaderText="Penalties" 
       SortExpression="Penalties" /> 
      <asp:BoundField DataField="Drop Goals" HeaderText="Drop Goals" 
       SortExpression="Drop Goals" /> 
      <asp:BoundField DataField="Yellow Cards" HeaderText="Yellow Cards" 
       SortExpression="Yellow Cards" /> 
      <asp:BoundField DataField="Red Cards" HeaderText="Red Cards" 
       SortExpression="Red Cards" /> 
     </Columns> 
     <FooterStyle BackColor="#CCCCCC" /> 
     <HeaderStyle BackColor="Black" Font-Bold="True" ForeColor="White" /> 
     <PagerStyle BackColor="#999999" ForeColor="Black" HorizontalAlign="Center" /> 
     <SelectedRowStyle BackColor="#000099" Font-Bold="True" ForeColor="White" /> 
     <SortedAscendingCellStyle BackColor="#F1F1F1" /> 
     <SortedAscendingHeaderStyle BackColor="#808080" /> 
     <SortedDescendingCellStyle BackColor="#CAC9C9" /> 
     <SortedDescendingHeaderStyle BackColor="#383838" /> 
    </asp:GridView> 
    <asp:SqlDataSource ID="SqlDataSource1" runat="server" 
     ConnectionString="<%$ ConnectionStrings:ConnectionString %>" 
     SelectCommand="SELECT * FROM [statstable]"></asp:SqlDataSource> 
+0

看。 http://stackoverflow.com/questions/702600/sorting-and-paging-with-gridview-asp-net, http://msdn.microsoft.com/en-us/library/hwf94875.aspx, http://www.netomatix.com/development/GridViewSorting.aspx – jlg

回答

0

我建議你看看這篇文章,扭轉上升/下降旗邏輯。

GridView sorting: SortDirection always Ascending

你的ASPX頁面將有一個GridView這樣的(特別關注的OnSorting部分):

<asp:GridView ID="grdHeader" AllowSorting="true" AllowPaging="false" 
    AutoGenerateColumns="false" Width="780" runat="server" 
    OnSorting="grdHeader_OnSorting" EnableViewState="true"> 
    <Columns>   
     <asp:BoundField DataField="Entitycode" HeaderText="Entity" SortExpression="Entitycode" />   
     <asp:BoundField DataField="Statusname" HeaderText="Status" SortExpression="Statusname" />   
     <asp:BoundField DataField="Username" HeaderText="User" SortExpression="Username" />  
    </Columns> 
</asp:GridView> 

你的代碼隱藏(aspx.cs),那麼將需要實現的方法grdHeader_OnSorting 。 GridViewSortEventArgs中的變量會告訴你用戶要求排序的方向。在你的情況,你會那麼做相反......如:

protected void grdHeader_OnSorting(object sender, GridViewSortEventArgs e)   
{    
    List<V_ReportPeriodStatusEntity> items = GetPeriodStatusesForScreenSelection(); 
    SortDirection dir = e.SortDirection == SortDirection.Ascending ? SortDirection.Descending : SortDirection.Ascending; 
    items.Sort(new Helpers.GenericComparer<V_ReportPeriodStatusEntity>(e.SortExpression, dir)); 
    grdHeader.DataSource = items;  
    grdHeader.DataBind(); 
} 

這裏items.Sort方法做的所有排序...所有你正在做的是採取這一排序結果和分配回你的數據源。

如果你想在如何排序的GridView的概念的更多信息,我建議你在看MSDN上的這個例子: http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.sort.aspx

讓我知道如果有什麼我可以做澄清。

+0

你看我的問題如下。我在發佈這篇文章之前已經閱讀過這篇文章,但有6或7個答案,全部投票結果並且互不相同。我對編程和ASP.NET仍然很陌生,但我並不完全瞭解所有的代碼。我不能相信那些被認爲是如此簡單的東西太複雜了(複雜的用在我的專業詞彙中)......更具體的建議......我真的花了整整一天的時間來解決這個問題,但無論我去哪裏,人們的代碼都相差很大。有人說這個,另一個人說。 –

+0

大衛,看到我上面的增加 –

+0

是的謝謝你。我像你推薦的那樣實現它,但是我得到了'使用指令或程序集引用丟失'的錯誤,用於以下行:V_ReportPeriodStatusEntity; GetPeriodStatusesForScreenSelection(); Helpers.Any建議? –

0

恐怕這是默認行爲,如果你想改變它,你必須在GridView上實現OnSorting事件,並根據排序表達式切換行爲。例如,如果排序表達式爲TEAM DESC,那麼您將排序TEAM ASC,反之亦然。

像這樣的東西(假設你的SelectCommand是沒有order by子句一個簡單的SELECT語句):

protected void GridView1_Sorting(Object sender, GridViewSortEventArgs e) 
    { 
    string originalSelectCommand = SqlDataSource1.SelectCommand; 
    if (e.SortDirection == "ASC")//sort data source in DESC 
    { 
     if(e.SortExpression=="Team") 
     { 
      SqlDataSource1.SelectCommand=SqlDataSource1.SelectCommand + " Order BY TEAM DESC";    
     } 
     else if(e.SortExpression=="Another Column") //etc 
     { 
     } 
    } 
    else //Sort data source in ASC 
    { 
    } 
    SqlDataSource1.Select(DataSourceSelectArguments.Empty); 
    GridView1.DataBind(); 
    SqlDataSource1.SelectCommand=originalSelectCommand;//revert back to original w/o order by 
    } 

所有你需要做的,您的標記是:

<asp:GridView ID="GridView1" runat="server" 
    OnSorting="GridView1_Sorting" 
    AllowSorting="True" 
    AutoGenerateColumns="False" BackColor="White" BorderColor="#999999" 
    BorderStyle="Solid" BorderWidth="1px" CellPadding="3" 
    DataSourceID="SqlDataSource1" ForeColor="Black" GridLines="Vertical" > 
    <AlternatingRowStyle BackColor="#CCCCCC" /> 

警告:以上代碼沒有經過測試,但我認爲它應該做你想做的。

+0

感謝您的回覆。 Visual Studio強調了紅色中的if(e.SortDirection ==「ASC」)語句,並表示:Operator ==不能應用於類型爲「Sytem.Web.UI.Webcontrols.SortDirection」和「String」的操作數。請記住,我對asp.net函數和編碼知之甚少,請儘量保持簡單和解釋性。每個人都假設我確切地知道他們在說什麼,並且我明白了代碼。如果我這樣做,我會問這個問題 –

0

我在另一個論壇上發現了一個解決方案,但它仍然存在缺陷 - 我想要的是默認第一次點擊列上的排序順序是降序而不是升序。但是當我再次點擊另一列時,它會將排序方向設置爲再次上升。無論是哪一列,每次點擊都會下降和上升。現在我真正想要的第一次點擊任何列是降序,如果我第二次點擊任何列,它應該是升序。例如:我有兩列,一個是工資,另一個是年齡。現在我點擊薪水,第一個排序方向是降序,而不是默認升序(這是代碼的作用)。現在當我點擊年齡時,它開關排序方向升序,我希望它保持不變,當我改變到另一列,但我應該再次點擊薪水第二次,它應該切換到升序(原因降序是第一次點擊)。有什麼建議麼?

驗證碼: `

public SortDirection GridViewSortDirection 
{ 
    get 
    { 
     if (ViewState["sortDirection"] == null) //if viewstate doesn't contain any value, assume SortDirection.Ascending(cause thats the asp default) 
      ViewState["sortDirection"] = SortDirection.Ascending; 
     return (SortDirection)ViewState["sortDirection"]; 
    } 
    set 
    { 
     ViewState["sortDirection"] = value; //Viewstate sort direction is set as a variable, so can contain either asc or desc 
    } 
} 
protected void GridView1_OnSorting(object sender, GridViewSortEventArgs e) 
{ 
    if (ViewState["sortDirection"] == null) 
    { 
     e.SortDirection = SortDirection.Descending; 
    } 
    else if (GridViewSortDirection == SortDirection.Ascending) 
    { 
     e.SortDirection = SortDirection.Descending; 
    } 
    else if (GridViewSortDirection == SortDirection.Descending) 
    { 
     e.SortDirection = SortDirection.Ascending; 
    } 

    GridViewSortDirection = e.SortDirection; 
} 

`

3

爲什麼容易時,它可以是複雜的,嗯傢伙?

protected void GridView1_OnSorting(object sender, GridViewSortEventArgs e) 
{ 
    // If you want to only switch default for some column, disable comment 
    //switch (e.SortExpression) 
    //{ 
    // case "MyDataField01": 
    // case "MyDataField03": 
      if (e.SortExpression != ((GridView)sender).SortExpression) 
      { 
       e.SortDirection = SortDirection.Descending; 
      } 
    //  break; 
    // default: 
    //  break; 
    //} 
} 

當然,在GridView的aspx中綁定OnSorting事件。來源:http://csc-technicalnotes.blogspot.com/2010/06/change-gridview-sortdirection-default.html

12
public partial class _Default : Page 
{ 
    protected void Page_Load(object sender, EventArgs e) 
    { 
     // Set your deault sort expression and direction. 
     if (String.IsNullOrEmpty(MyGridView.SortExpression)) MyGridView.Sort("SortExpression", SortDirection.Ascending); 
    } 
} 
+0

我有一個問題,首先點擊列標題按列排序不會改變排序方向。結果是,當第一次創建ListView時,排序select方法獲得一個空的排序表達式。以上將解決這個問題。 –

0

我周圍的Googling,因爲我有同樣的問題,在玩了一圈,發現,如果我說「ORDER BY [字段名稱]」在我的SQL語句,並啓用了排序,當我點擊標題,它會顛倒任何列的順序!我認爲這是一條非常古老的線索,但也許這對未來的其他人也有幫助。隨着深入的答案更,這是我爲我的數據源代碼:

<asp:AccessDataSource ID="AccessDataSource1" runat="server" 
    DataFile="~/App_Data/webvideos.mdb" 
    DeleteCommand="DELETE FROM [Docs] WHERE [ID] = ?" 
    InsertCommand="INSERT INTO [Docs] ([ID], [Filename], [Label], [Section], [Index]) VALUES (?, ?, ?, ?, ?)" 
    SelectCommand="SELECT * FROM [Docs] ORDER BY ID" 
    UpdateCommand="UPDATE [Docs] SET [Filename] = ?, [Label] = ?, [Section] = ?, [Index] = ? WHERE [ID] = ?"> 

這是我的GridView控件:這裏

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" 
     DataKeyNames="ID" DataSourceID="AccessDataSource1" AllowPaging="True" 
     PageSize="20" AllowSorting="True"> 
     <Columns> 
      <asp:CommandField ShowDeleteButton="True" ShowEditButton="True" /> 
      <asp:BoundField DataField="ID" HeaderText="ID" InsertVisible="False" 
       ReadOnly="True" SortExpression="ID" /> 
      <asp:BoundField DataField="Label" HeaderText="Label" SortExpression="Label" /> 
      <asp:BoundField DataField="Filename" HeaderText="Filename" 
       SortExpression="Filename" /> 
      <asp:BoundField DataField="Section" HeaderText="Section" 
       SortExpression="Section" /> 
      <asp:BoundField DataField="Index" HeaderText="Index" SortExpression="Index" /> 
     </Columns> 
    </asp:GridView>