This article describes how to programmatically highlight a specific row in the DataGrid control (6.0).
The same procedure can be applied in Visual Basic 5.0 using the DBGrid
In order to highlight a specific row in the DataGrid you need to specify
the bookmark of the target record within the recordset of your data source.
You need to add this bookmark to the collection of bookmarks.
Each bookmark previously appended to the collection shows in the range of
selected rows on your DataGrid control. You need to explicitly remove these
rows from the collection before appending the bookmark for the record you
wish to highlight.
The following Visual Basic 6.0 sample code demonstrates the process of
searching for a record and then highlighting the hit within your grid:
- Start a new Standard EXE project in Visual Basic. Form1 is created by
- Select Components on the Project menu. Select "Microsoft DataGrid
Control 6.0 (OLE DB)." Select Project References and add "Microsoft
ActiveX Data Objects 2.x Library."
- Add a CommandButton to your form; the default is Command1. Add a
DataGrid control to your form; the default is DataGrid1.
- Place the following code in the General Declaration section of Form1:
Dim cn As New ADODB.Connection
Dim rs As New ADODB.Recordset
Dim cmd As New ADODB.Command
Dim i As Integer
Dim FindLastName As String
Private Sub Command1_Click()
' Remove previously saved bookmark from collection
If (DataGrid1.SelBookmarks.Count <> 0) Then
' Prompt user for desired author's last name
FindLastName = InputBox("Please enter the author's last name you
want to search for", "Find")
rs.Find "au_lname = '" & FindLastName & "'", , , 1
' Append your bookmark to the collection of selected rows
Private Sub Form_Load()
' Open your ADO connection where "Pubs" is an ODBC DSN that
' points to pubs database in SQL Server
' Create your command to query for all records in Authors table
.ActiveConnection = cn
.CommandText = "select * from authors"
' Open your recordset
' Set rs properties
.CursorType = adOpenKeyset
.LockType = adLockOptimistic
' Call open using active command
' Populate the DataGrid providing rs as the data source
Set DataGrid1.DataSource = rs
- Press the F5 key to run the application. Click the CommandButton and
enter an Author's last name. Note it moves the cursor to the Author
selected and highlights the entire row.
Article ID: 195472 - Last Review: August 3, 2005 - Revision: 2.1
- Microsoft Visual Basic Enterprise Edition for Windows 6.0
|kbconfig kbctrl kbhowto kbsetup KB195472|