<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ListViewSort.aspx.cs" Inherits="ListViewSort" %>
<html>
<head runat="server">
<title>ListViewSort</title>
</head>
<body>
<form id="form1" runat="server">
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="SELECT [ProductID], [ProductName], [UnitPrice]
FROM [Products]
Order by UnitPrice ASC ">
</asp:SqlDataSource>
<div style="width:500px;float:left;">
<asp:ListView ID="ListView1" runat="server" DataSourceID="SqlDataSource1" >
<ItemTemplate>
<tr>
<td>
<asp:Label ID="ProductIDLabel" runat="server" Text='<%#Eval("ProductID") %>' />
</td>
<td>
<asp:Label ID="ProductNameLabel" runat="server" Text='<%#Eval("ProductName") %>' />
</td>
<td>
<asp:Label ID="UnitPriceLabel" runat="server" Text='<%#Eval("UnitPrice") %>' />
</td>
</tr>
</ItemTemplate>
<LayoutTemplate>
<table ID="itemPlaceholderContainer" runat="server" border="1">
<tr runat="server" style="background-color:#DCDCDC;color: #000000;">
<th>
<asp:LinkButton Text="產品編號" CommandName="sort" CommandArgument="ProductID" runat="server" />
</th>
<th>
<asp:LinkButton Text="產品名稱" CommandName="sort" CommandArgument="ProductName" runat="server" />
</th>
<th>
<asp:LinkButton Text="單價" CommandName="sort" CommandArgument="UnitPrice" runat="server" />
</th>
</tr>
<tr ID="itemPlaceholder" runat="server">
</tr>
<tr>
<td colspan="3" runat="server">
<asp:DataPager ID="DataPager1" runat="server" PageSize="20">
<Fields>
<asp:NextPreviousPagerField ButtonType="Button" ShowFirstPageButton="True" ShowLastPageButton="True" />
</Fields>
</asp:DataPager>
</td>
</tr>
</table>
</LayoutTemplate>
</asp:ListView>
</div>
</form>
</body>
</html>
重點就是在<table>的標題列,把想要排序欄位的標題弄成Button,然後CommandName=”sort”,CommandArgument=”欄位名稱”
ListView就可以排序了
只是很奇妙的是,因為SQL語法Order by UnitPrice ASC,所以第一次按單價按鈕沒有反應,要按第二次才會排序。
第一次執行網頁(確實按照UnitPrice遞增排序)
_a18de264-e3ff-4457-8d53-125ef31084f0.png)
按下產品編號後,依產品編號遞增排序

再按一次產品編號,依產品編號遞減排序

點下一頁後,排序仍然依產品編號遞減
沒有留言:
張貼留言