DataGrid排序、分頁、選擇

HTML

  • 添加一個DataGrid,命名爲dgOrder
  • 添加了一個模板列,模板列裏放一個名爲CbCheckBox控件。此列用來實現選擇
  • 爲要排序的每個列加上排序表達式SortExpression
  • 利用列的DataFormatString來格式化列,象DataFormatString="{0:d}"顯示日期格式。
  • 設置PageSize="15"每頁顯示15行數據,AllowPaging="True" 爲允許分頁

<?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" />

 

整個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="#<?xml:namespace prefix = st1 ns = "urn:schemas-microsoft-com:office:smarttags" />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>

                     </asp:BoundColumn>

                     <asp:BoundColumn DataField="ShipAddress" SortExpression="ShipAddress" HeaderText="ShipAddress">

                            <HeaderStyle Width="480px"></HeaderStyle>

                     </asp:BoundColumn>

              </Columns>

              <PagerStyle HorizontalAlign="Center" ForeColor="Black" Position="TopAndBottom" BackColor="White" Mode="NumericPages"></PagerStyle>

       </asp:datagrid>

</form>

 

 

 

後臺類添加以下代碼:

 

Imports System.Data.SqlClient

 

'得到數據視圖,參數爲要排序的列

Private Function GetDv(ByVal strSort As String) As DataView

        '定義數據庫連接

        Dim dv As DataView

        Dim CN As New SqlConnection()

        Try

            '初始化連接字符串

            CN.ConnectionString = "data source=pmserver;initial catalog=Northwind;persist security info=False;user id=sa;Password=sa;"

            CN.Open()

'NorthWind得到orders表的數據

            Dim adp As SqlDataAdapter = New SqlDataAdapter("select * from orders", CN)

            Dim ds As New DataSet()

            adp.Fill(ds)

            '得到數據視圖

            dv = ds.Tables(0).DefaultView

        Catch ex As Exception

#If DEBUG Then

            Session("Error") = ex.ToString()

            Response.Redirect("../error.aspx")        '跳轉程序的公共錯誤處理頁面

#End If

        Finally

            '關閉連接

            CN.Close()

        End Try

        '排序

        dv.Sort = strSort

        Return dv

    End Function

 

    Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

        If Not IsPostBack Then

            ViewState("strSort") = "orderid"

            dgOrder.DataSource = GetDv(ViewState("strSort").ToString())

            dgOrder.DataBind()

        End If

    End Sub

       '排序

    Private Sub dgOrder_SortCommand(ByVal source As Object, ByVal e As System.Web.UI.WebControls.DataGridSortCommandEventArgs) Handles dgOrder.SortCommand

        dgOrder.CurrentPageIndex = 0

          '得到排序的列

        ViewState("strSort") = e.SortExpression.ToString()

        dgOrder.DataSource = GetDv(ViewState("strSort").ToString())

        dgOrder.DataBind()

    End Sub

 

       '分頁

    Private Sub dgOrder_PageIndexChanged(ByVal source As Object, ByVal e As System.Web.UI.WebControls.DataGridPageChangedEventArgs) Handles dgOrder.PageIndexChanged

          '得到分頁的頁號

        dgOrder.CurrentPageIndex = e.NewPageIndex

        dgOrder.DataSource = GetDv(ViewState("strSort").ToString())

        dgOrder.DataBind()

    End Sub

運行結果如下圖所示:(點擊列標頭可以排序)

<?xml:namespace prefix = v ns = "urn:schemas-microsoft-com:vml" />

 

爲了知道用戶選擇的是哪些記錄,我們可以利用DataGridItemFindControl得到CheckBox的值,我們來添加一個按鈕,再寫如下代碼:

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

        Dim item As DataGridItem

        Dim StrScript As String

        StrScript = "<script language=javascript>alert('"

          '循環表格的項,FindControl

        For Each item In Me.dgOrder.Items

            If CType(item.FindControl("cb"), System.Web.UI.WebControls.CheckBox).Checked Then

                Try

                    StrScript += item.Cells(1).Text & Space(2)

                Catch ex As Exception

                End Try

            End If

        Next

        StrScript += "被選擇!')</script>"

        RegisterClientScriptBlock("系統消息", StrScript)

    End Sub

 

上面的代碼RegisterClientScriptBlock添加Java Script腳本彈出對話框。(其實Vb Script的對話框比Java Script的對話框多更多的顯示和控制方式,但Netscape的瀏覽器不支持,大家可根據相應的項目在程序裏選擇用哪種腳本)。

 

 

 

 

總結:

DataGrid是我們常用的Web 控件,有時我們還可以和DataList混合使用,通過修改HTML頁,可以達到好的頁面效果。上面只是一個例子,爲了便於清楚整個過程,我把數據訪問部分(SQL)寫到了頁面中。在軟件開發中,我們一般把訪問數據的部分寫成數據層,頁面調用數據層得到數據,這樣邏輯清晰,修改和維護都很方便。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章