How to Find a row in DataView

The DataView in ADO.NET provides a flexible mechanism for creating different views of the data stored in a DataTable. By initializing a new instance of the DataView class using its constructor, we can establish a DataView that is specifically associated with a particular DataTable. This constructor accepts the DataTable as an argument, enabling us to define the underlying data source for the DataView.

DefaultView property

Alternatively, we can create a DataView by referencing the DefaultView property of the DataTable. This property automatically provides a DataView associated with the DataTable, simplifying the DataView creation process.

Furthermore, it's worth noting that we have the capability to create multiple DataViews for a single DataTable. This allows us to define various views of the data, each with its own sorting, filtering, and searching criteria.

When working with a DataView, we can perform searches based on the sort key values. The DataView class offers a Find method, which allows us to search for a specific value or a combination of values within the DataView. This method returns an integer that represents the index of the DataRowView that matches the search criteria. If multiple rows match the search criteria, only the index of the first matching DataRowView is returned. In cases where no matches are found, the Find method returns -1.

Dim index As Integer = DataView.Find("Product5")
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(connectionString) Try connection.Open() command = New SqlCommand(sql, connection) adapter.SelectCommand = command adapter.Fill(ds, "Find Row DataView") adapter.Dispose() command.Dispose() connection.Close() dv = New DataView(ds.Tables(0)) dv.Sort = "Product_Name" Dim index As Integer = dv.Find("Product5") If index = -1 Then MsgBox("Item Not Found") Else MsgBox(dv(index)("Product_id").ToString() & " " & dv(index)("Product_Name").ToString()) End If Catch ex As Exception MsgBox(ex.ToString) End Try End Sub End Class

Conclusion

DataView provides a versatile means of creating customized views of the data stored in a DataTable. By employing the DataView constructor or the DefaultView property, we can establish DataViews that are specifically linked to a DataTable. Additionally, the Find method empowers us to search for specific data within a DataView based on the defined sort key values, enhancing our ability to manipulate and access data effectively.