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


Comments

Guest Author: eLobrino23 Nov 2012

"drFind" is undeclared. ouch!

Guest Author: Kathy05 Apr 2013

How do i then enter a new search name on form1 and return to form2 so that I do not pull up 1st record in the database. I click next and can then see the new search but show the 1st record initially.



  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: