[AccessD] Setting listbox selection

A.D.TEJPAL adtp at airtelbroadband.in
Thu Aug 16 14:42:33 CDT 2007


Chris,

    There is an interesting solution to your reported problem in clearing a single-select list box. In your existing code, just insert the following as the first statement in click event of command button.

    Me.List0.Requery

    In fact the task can be made drastically simpler by using the following sample code in click event of the command button. It uses only two statements and does away with the need for a subroutine looping through all the rows of a list box.

======================
Private Sub CmdClear_Click()
    Me.List0.Requery
    Me.List0 = Null
End Sub
======================

Best wishes,
A.D.Tejpal
--------------

  ----- Original Message ----- 
  From: Christopher Jeris 
  To: Access Developers discussion and problem solving 
  Sent: Thursday, August 16, 2007 22:54
  Subject: [AccessD] Setting listbox selection


  -----BEGIN PGP SIGNED MESSAGE-----
  Hash: SHA1

  Hi everyone,

  Some behavior of the .Selected attribute of the ListBox control is
  baffling me.  Specifically, setting the .Selected attribute of a
  single-select listbox element, when that element is not in the currently
  viewable region of a scrollable listbox, does not appear to work.

  Here's a test case on Access 2002 SP3.

  Create a form containing a single listbox List0, with
    Row Source Type = Value List
    Row Source = 0;1;2;3;4;5;6;7;8;9
  Size the listbox so that not all the rows are visible (there is a scroll
  bar).

  and a single command button Command2, with the following code:

  Private Sub EraseSelection(box As ListBox)
      Dim i As Long
      For i = 0 To box.ListCount - 1
          box.Selected(i) = False
      Next i
  End Sub

  Private Sub Command2_Click()
      EraseSelection Me!List0
      If Me!List0.ItemsSelected.Count > 0 Then
          MsgBox Me!List0.ItemsSelected(0)
      End If
  End Sub

  To test:
  Select an element in the listbox.  Click Command2.  The selection
  disappears.

  Select an element in the listbox.  Scroll the listbox so that the
  highlighted row is ENTIRELY beyond the viewable region (the problem does not occur if the highlight is partially visible).  Click Command2.  I get two MsgBoxes; the first one gives the highlighted row; the second one gives -1.

  In other words, setting the selected item of a listbox using the
  .Selected property may silently fail, depending entirely on a fact (the
  view region of the listbox) which I know no way to find out in code!

  What's going on here, and what should I be doing instead?

  thanks much, Chris Jeris


More information about the AccessD mailing list