Hi
I need the code in VB6 to display data from a database in a listbox
i tried the following code but its not working
Do While Not rec2.EOF
List1.ItemData(List6.NewIndex) = rec2.Fields(4)
rec2.MoveNext

' i even tried
Do While Not rec2.EOF
List1.ItemData rec2.Fields(4)
rec2.MoveNext

Dani AI

Generated

Brief diagnosis and next steps

was trying to shove a field value into a ListBox.ItemData slot; that property is intended for a numeric (Long) value only, so text or variants will fail. ’s direction to add visible items is the right idea — add the text you want shown, and use ItemData only for a numeric key (after converting and checking for Null).

How to show one or many fields

  • For a single visible column: iterate the open recordset, add the display string for each record, and (if you need to remember the record’s numeric ID) store that ID in ItemData after converting to a Long and checking for Null. Use field names (e.g. rs.Fields("Name")) to make code clearer and safer than numeric indexes.
  • For multiple columns: use a control that supports columns (ListView in report mode, MSFlexGrid or DataGrid). Those controls let you create column headers and put separate fields into separate columns; they keep rows together (no need to synchronize separate listboxes).

Example: ListView (VB6) pattern

' set up columns
ListView1.View = lvwReport
ListView1.ColumnHeaders.Clear
ListView1.ColumnHeaders.Add , , "ID", 50
ListView1.ColumnHeaders.Add , , "First", 120
ListView1.ColumnHeaders.Add , , "Last", 120

' populate from an open recordset rs
Dim li As ListItem
Do While Not rs.EOF
    Set li = ListView1.ListItems.Add(, , CStr(rs!ID))
    li.SubItems(1) = CStr(rs!FirstName)
    li.SubItems(2) = CStr(rs!LastName)
    rs.MoveNext
Loop

Practical tips and traps

  • Check for Null before converting fields. A type-mismatch on ItemData usually means the value was not numeric.
  • Ensure the recordset is open and you check .EOF/.BOF.
  • If you must use multiple listboxes side-by-side, add items to each one inside the same loop and synchronize selection by copying ListIndex on Click.
  • Consider switching to a grid/ListView for tabular data; it’s less error-prone and displays separate fields cleanly.

Do While Not rec2.EOF
List1.AddItem rec2.Fields(4)
rec2.MoveNext

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.