如何在ASP.NET里用DataView来达到DataGrid控件里的Column Sorting效果。

(華版)

这幾天一直在钻研ADO.NET对象和DataGrid控件的基本功能,以下是一点点收获并何大家分享分享。

一般在WinForm里的DataGrid控件都是有提供Column Sorting的功能,但是在WebForm里就没了。。。其实我们可以用ADO.NET对象里的DataView来达到相同的效果;只是需要写多一点点的代码而已。另外,我们也先要把DataGrid控件的AllowSorting属性值改去True。

在Code Behind Page里,我们只需要在DataGrid1_SortCommand事件里读取所选的Column的名字;然后就如平常从数据苦里读取资料一样,只是将DataSet里的数据转到一个新的DataView对象,并把DataView.Sort属性值改为之前所得到的Column名字。那么,最后一步当然就是把DataView bind到DataGrid控件里。。。这样就大功告成了!

 

    Private SortString As String
    
Private PageIndex As Integer = -1

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

        
If Not Page.IsPostBack Then
            LoadDataFromSql()
        
End If

    
End Sub


    
Private Sub LoadDataFromSql()

        
'声明变量
        Dim cn As SqlConnection
        
Dim da As SqlDataAdapter
        
Dim ds As DataSet
        
Dim dv As System.Data.DataView

        
Try
            
'连接SQL数据库
            cn = New SqlConnection("Data Source=localhost;Initial Catalog=NorthWind;Integrated Security=true;")
            cn.Open()

            
'用SqlDataAdapter来转载数据库回返的资料进DataSet对象里
            ds = New DataSet
            da 
= New SqlDataAdapter("select CustomerID, CompanyName, ContactName from customers", cn)
            da.Fill(ds, 
"Customers")

            
'建立新DataView对象并用来Sort所选的Column数据 
            dv = New System.Data.DataView(ds.Tables("Customers"))
            dv.Sort 
= SortString

            
'把所得到的DataView对象绑定到DataGrid控件去
            DataGrid1.DataSource = dv
            
If PageIndex <> -1 Then DataGrid1.CurrentPageIndex = PageIndex
            DataGrid1.DataBind()

        
Catch ex As SqlException
            
'显示错误信息
            lblSqlError.Text = "Error No. (" & ex.Number & "), Line No. (" & ex.LineNumber & "), " & ex.Message

        
Finally
            
'释放所用的资源
            If Not cn Is Nothing Then
                
If cn.State <> ConnectionState.Closed Then cn.Close()
                cn 
= Nothing
            
End If

        
End Try

    
End Sub


    
Private Sub DataGrid1_SortCommand(ByVal source As ObjectByVal e As System.Web.UI.WebControls.DataGridSortCommandEventArgs) Handles DataGrid1.SortCommand

        
'此是DataGrid里的Column Header的Click事件过程。

        
'读取所选Column名字
        SortString = e.SortExpression.ToString()
        
'刷新显示的资料
        LoadDataFromSql()

    
End Sub


    
Private Sub DataGrid1_PageIndexChanged(ByVal source As ObjectByVal e As System.Web.UI.WebControls.DataGridPageChangedEventArgs) Handles DataGrid1.PageIndexChanged

        
'此是DataGrid里的Page Index的更换事件过程。

        
'读取所选的Page index
        PageIndex = e.NewPageIndex
        
'刷新显示的资料
        LoadDataFromSql()

    
End Sub

點撃下載程式代碼
posted on 2005-04-01 17:08  克仔  阅读(1666)  评论(6编辑  收藏  举报