'得到数据视图,参数为要排序的列
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
运行结果如下图所示:(点击列标头可以排序)
为了知道用户选择的是哪些记录,我们可以利用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('"
'循环表格的项,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)写到了页面中。在软件开发中,我们一般把访问数据的部分写成数据层,页面调用数据层得到数据,这样逻辑清晰,修改和维护都很方便。</script>