How to sort DataView

The DataView provides different views of the data stored in a DataTable. DataView can be used to sort, filter, and search data in a DataTable , additionally we can add new rows and modify the content in a DataTable. DataViews can be created and configured at both design time and run time . Changes made to a DataView affect the underlying DataTable automatically, and changes made to the underlying DataTable automatically affect any DataView objects that are viewing that DataTable.

We can sort single or multiple fields in a DataView , also we can specify the sort order like ASC (ascending) and DESC (descending) . The following example creates a View and apply sort on the column Product_Price in descending order. Create a new VB.NET project and drag a DataGridView and a Button on default Form Form1 , and copy and paste the following Source Code on button click event.




Imports System.Data.SqlClient
Public Class Form1
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim connetionString As String
        Dim connection As SqlConnection
        Dim command As SqlCommand
        Dim adapter As New SqlDataAdapter
        Dim ds As New DataSet
        Dim dv As DataView
        Dim sql As String
		connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password"
        sql = "Select  * from product"
        connection = New SqlConnection(connetionString)
        Try
            connection.Open()
            command = New SqlCommand(sql, connection)
            adapter.SelectCommand = command
            adapter.Fill(ds, "Sort DataView")
            adapter.Dispose()
            command.Dispose()
            connection.Close()

            dv = New DataView(ds.Tables(0), "Product_Price > 100", "Product_Price Desc", DataViewRowState.CurrentRows)
            DataGridView1.DataSource = dv

        Catch ex As Exception
            MsgBox(ex.ToString)
        End Try
    End Sub
End Class

 ADO.NET DataView - Related Contents



.