Often when you store records in a database, you may create a unique
ID number to go along with that record. In Visual Basic, you can use
the ListView or TreeView controls to display these records. It's
only natural that you might want to use each records numeric ID
value as each item's Key value in the control. However, if you've
ever tried to add a number key to either of these controls, then
you know that Visual Basic generates an invalid key error.
This error occurs because the ListView control won't accept all-
numeric keys-even if they're technically strings. As a work-around,
if you want to add all-numeric Ids to the control, you'll need to
append an alpha character to the end of it. The following code
snippet illustrates how you might go about doing so. This code
assumes you're using a ListView in report mode with two columns
total, and that you've created a recordset object.
If Not Rst.EOF Then
With Rst
.MoveFirst
Do
Set itm =
ListView1.ListItems.Add(Key:=.Fields _
("txtID")
& "K", Text:=.Fields("sintRank"))
itm.SubItems(1) = .Fields("txtCounty")
.MoveNext
Loop Until .EOF
End With
End If
To retrieve the true Id value from the Key property, simply use the
Val() function to strip the character back out, as in
MsgBox "Key: " & itm.Key & vbNewLine _
& "ID value: " & Val(itm.Key)
If you were to put an alpha character at the beginning of the ID value,
the Val() function would return 0.