'得到數(shù)據(jù)視圖,參數(shù)為要排序的列
Private Function GetDv(ByVal strSort As String) As DataView
'定義數(shù)據(jù)庫(kù)連接
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)程序的公共錯(cuò)誤處理頁(yè)面
#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
'分頁(yè)
Private Sub dgOrder_PageIndexChanged(ByVal source As Object, ByVal e As System.Web.UI.WebControls.DataGridPageChangedEventArgs) Handles dgOrder.PageIndexChanged
'得到分頁(yè)的頁(yè)號(hào)
dgOrder.CurrentPageIndex = e.NewPageIndex
dgOrder.DataSource = GetDv(ViewState("strSort").ToString())
dgOrder.DataBind()
End Sub
運(yùn)行結(jié)果如下圖所示:(點(diǎn)擊列標(biāo)頭可以排序)
為了知道用戶選擇的是哪些記錄,我們可以利用DataGridItem的FindControl得到CheckBox的值,我們來(lái)添加一個(gè)按鈕,再寫如下代碼:
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)表格的項(xiàng),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腳本彈出對(duì)話框。(其實(shí)Vb Script的對(duì)話框比Java Script的對(duì)話框多更多的顯示和控制方式,但Netscape的瀏覽器不支持,大家可根據(jù)相應(yīng)的項(xiàng)目在程序里選擇用哪種腳本)。
總結(jié):
DataGrid是我們常用的Web 控件,有時(shí)我們還可以和DataList混合使用,通過(guò)修改HTML頁(yè),可以達(dá)到好的頁(yè)面效果。上面只是一個(gè)例子,為了便于清楚整個(gè)過(guò)程,我把數(shù)據(jù)訪問(wèn)部分(SQL)寫到了頁(yè)面中。在軟件開(kāi)發(fā)中,我們一般把訪問(wèn)數(shù)據(jù)的部分寫成數(shù)據(jù)層,頁(yè)面調(diào)用數(shù)據(jù)層得到數(shù)據(jù),這樣邏輯清晰,修改和維護(hù)都很方便。</script>