讓Asp.NET的DataGrid可排序、可選擇、可分頁
2024-07-10 12:40:35
供稿:網友
DataGrid是Asp.NET中的一個重要的控件,經常我們都將DataGrid做成可分頁的和可排序的,有時還需要加上選擇功能。這些都是經常需要用到的方法,其實是比較簡單的。
設計思路:
為了方便起見,我們連接SQL Server 2000的NorthWind數據庫的Orders表,從數據庫里得到此表的數據視圖。利用DataGrid的SortCommand事件實現排序。用一個模板列加上CheckBox控件實現選擇。可用DataGrid的屬性生成器的“分頁”選項或者自己修改HTML實現分頁。
HTML:
添加一個DataGrid,命名為dgOrder。
添加了一個模板列,模板列里放一個名為Cb的CheckBox控件。此列用來實現選擇
為要排序的每個列加上排序表達式SortExpression。
利用列的DataFormatString來格式化列,象DataFormatString="{0:d}"顯示日期格式。
設置PageSize="15"每頁顯示15行數據,AllowPaging="True" 為允許分頁 。
整個HTML頁代碼:
<form id="Form1" method="post" runat="server">
<asp:datagrid id="dgOrder" runat="server" Height="515px" Width="718px" AutoGenerateColumns="False" AllowSorting="True" CellPadding="4" BorderWidth="1px" BorderColor="#A0ABEB" PageSize="15" BorderStyle="Solid" BackColor="White" GridLines="Vertical" ForeColor="Black" AllowPaging="True" ShowFooter="True">
<SelectedItemStyle ForeColor="White" BackColor="Black"></SelectedItemStyle>
<AlternatingItemStyle BackColor="#EEEEEE"></AlternatingItemStyle>
<HeaderStyle HorizontalAlign="Center" ForeColor="White" BorderColor="#6876C5" BackColor="#6876C5"></HeaderStyle>
<FooterStyle ForeColor="White" BackColor="#6876C5"></FooterStyle>
<Columns>
<asp:TemplateColumn>
<ItemTemplate>
<FONT face="宋體">
<asp:CheckBox id="Cb" runat="server"></asp:CheckBox></FONT>
</ItemTemplate>
</asp:TemplateColumn>
<asp:BoundColumn DataField="orderid" SortExpression="orderid" HeaderText="ID">
<HeaderStyle Width="180px"></HeaderStyle>
</asp:BoundColumn>
<asp:BoundColumn DataField="ShipCountry" SortExpression="ShipCountry" HeaderText="ShipCountry">
<HeaderStyle Width="180px"></HeaderStyle>
</asp:BoundColumn>
<asp:BoundColumn DataField="ShippedDate" SortExpression="ShippedDate" HeaderText="ShippedDate" DataFormatString="{0:d}">
<HeaderStyle Width="180px"></HeaderStyle>
</asp:BoundColumn>
<asp:BoundColumn DataField="Freight" SortExpression="Freight" HeaderText="Freight">
<HeaderStyle Width="180px"></HeaderStyle>