How to Find a row in DataView
The DataView provides different views of the data stored in a DataTable. The constructor for the DataView class initializes a new instance of the DataView class and accepts the DataTable as an argument. We can create DataView in two ways. Either we can use the DataView constructor, or we can create a reference to the DefaultView property of the DataTable. We can create multiple DataViews for any given DataTable.
We can search in a DataView according to the sort key values by using the Find method . The Find method returns an integer with the index of the DataRowView that matches the search criteria. If more than one row matches the search criteria, only the index of the first matching DataRowView is returned. If no matches are found, Find returns -1
Dim index As Integer = DataView.Find("Product5")
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, "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
|
|