How to sort DataView

The DataView in ADO.NET offers various views of the data stored in a DataTable, allowing for sorting, filtering, and searching operations on the data. Additionally, it provides the ability to add new rows and modify the content of the underlying DataTable.


DataViews can be created and configured at both design time and runtime, depending on the specific requirements of the application. Any changes made to a DataView will automatically reflect in the associated DataTable, and vice versa. This ensures synchronization and consistency between the DataView and the DataTable.

Sort data in a DataView

To sort data in a DataView, you can specify single or multiple fields/columns. Moreover, you have the flexibility to define the sort order as ascending (ASC) or descending (DESC). For example, let's consider a scenario where we create a new DataView in a VB.NET project. On a default Form named Form1, we add a DataGridView and a Button. Upon clicking the button, we can apply sorting on the "Product_Price" column in descending order. To implement this, you can use the following source code:

Private Sub Button_Click(sender As Object, e As EventArgs) Handles Button1.Click ' Assuming you have a DataTable named "dataTable" containing the required data ' Create a DataView using the DataTable Dim dataView As New DataView(dataTable) ' Sort the data based on the "Product_Price" column in descending order dataView.Sort = "Product_Price DESC" ' Bind the DataView to the DataGridView for display DataGridView1.DataSource = dataView End Sub

By following this example and running the project, you will be able to see the sorted data in the DataGridView control.

Full Source VB.NET
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