Saturday, July 4, 2009

Search For Records in Data Table

The following VB.Net code is used to find for a particular record in the data table based on specific column.

The Find Method of Data Table does the trick.

It will return the Matching Data Row if matching record exists.



Imports System.Data.SqlClient 'Required name space for sql connection

Private Sub PopulateDataGrid()

'Variables Declaration
Dim ConnString As String
Dim conn As SqlConnection

Dim da As SqlDataAdapter
Dim ds As New DataSet
Dim SqlCmd As SqlCommand


ConnString = "Server = localhost;Database = EmployeeDB; Integrated Security = SSPI;"

conn = New SqlConnection(strConn)

da = New SqlDataAdapter("Select * from Employees", conn)
da.Fill(ds, "Employees")

ds.Tables(0).PrimaryKey = New DataColumn(ds.Tables(0).Columns("FirstName"))
DataGrid1.DataSource = ds.Tables(0)



End Sub

'Check For employee with the First Name as the passed name
Private Function CheckForEmployee (ByVal searchName As String) As Boolean


Dim drMatchRow As DataRow

'Find For Particular Employee With the given name
drMatchRow = ds.Tables(0).Rows.Find(searchName)


If drMatchRow Is Nothing Then
Return False
Else
lblMessage.Text = drFind.Item("EmployeeID")
Return True
End If


End Function





CheckForEmployee ("Jack") will return "2001" - Employee Id of Jack


Just for simplicity I have given one key column. But in real scenario, we need to use combination of Columns as Key.

No comments:

Post a Comment