How to Filter DataView

The DataView in ADO.NET provides a powerful feature that allows you to create various customized views of the data stored in a DataTable. These views offer flexibility in terms of how the data is displayed and manipulated. With a DataView, you can sort, filter, and search the data within a DataTable. Additionally, you have the capability to add new rows and modify the content of the DataTable.

DefaultView property

There are two ways to create a DataView. Firstly, you can use the DataView constructor to create a new instance of the DataView class, specifying the desired parameters such as the DataTable and any necessary filter criteria. Alternatively, you can create a reference to the DefaultView property of the DataTable, which automatically provides a DataView with the default settings.

Now, let's consider an example that demonstrates the usage of DataView. Suppose you want to create a view that displays all product details where the product price is less than 500.

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, "Filter DataView") adapter.Dispose() command.Dispose() connection.Close() dv = New DataView(ds.Tables(0), "Product_Price < = 500", "Product_Name", DataViewRowState.CurrentRows) DataGridView1.DataSource = dv Catch ex As Exception MsgBox(ex.ToString) End Try End Sub End Class

This example showcases the power of DataViews in customizing and manipulating data from a DataTable. By applying filters and creating specialized views, you can effectively present data based on specific criteria, enhancing the user experience and making data analysis more convenient.