'得到數(shù)據(jù)視圖,參數(shù)為要排序的列
Private Function GetDv(ByVal strSort As String) As DataView
'定義數(shù)據(jù)庫連接
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表的數(shù)據(jù)
Dim adp As SqlDataAdapter = New SqlDataAdapter("select * from orders", CN)
Dim ds As New DataSet()
adp.Fill(ds)
'得到數(shù)據(jù)視圖
dv = ds.Tables(0).DefaultView
Catch ex As Exception
#If DEBUG Then
Session("Error") = ex.ToString()
Response.Redirect("../error.aspx") '跳轉(zhuǎn)程序的公共錯誤處理頁面
#End If
Finally
'關(guān)閉連接
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
運行結(jié)果如下圖所示:(點擊列標(biāo)頭可以排序)
為了知道用戶選擇的是哪些記錄,我們可以利用DataGridItem的FindControl得到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('"
'循環(huán)表格的項,F(xiàn)indControl
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("系統(tǒng)消息", StrScript)
End Sub
上面的代碼RegisterClientScriptBlock添加Java Script腳本彈出對話框。(其實Vb Script的對話框比Java Script的對話框多更多的顯示和控制方式,但Netscape的瀏覽器不支持,大家可根據(jù)相應(yīng)的項目在程序里選擇用哪種腳本)。
總結(jié):
DataGrid是我們常用的Web 控件,有時我們還可以和DataList混合使用,通過修改HTML頁,可以達到好的頁面效果。上面只是一個例子,為了便于清楚整個過程,我把數(shù)據(jù)訪問部分(SQL)寫到了頁面中。在軟件開發(fā)中,我們一般把訪問數(shù)據(jù)的部分寫成數(shù)據(jù)層,頁面調(diào)用數(shù)據(jù)層得到數(shù)據(jù),這樣邏輯清晰,修改和維護都很方便。</script>