Tech Note 12: ListView Control

March 07, 2007

© NSB Corporation. All rights reserved.

NSListView ActiveX Control

This control is part of NS BASIC Controls package. Please see its documentation to get full information about this package.


1. Overview

The NSListView objects
Object model diagram
General notes and remarks

2. Object Reference

NSListView
ListItems
ListItem
SubItems
SubItem
Columns
Column
ColumnItems
Results

3. Using the NSListView control

1. Overview and architecture

The NSListView control exposes the Windows ListView control for the NSBasic applications. For that purpose it has internal object structure in which every ListView element is exposed to the application as an object with appropriate methods and properties.

IMPORTANT: The NSListView object does not currently work from the NS Basic ToolBox. To use this control, use an AddObject statement in your Form_Load routine and set the properties you need in code. See the examples for sample code.

The NSListView objects

The example lines below assume you have AddObject "NSBasic.comctl.ListView", "MyListView", ...

NSListView The root object which represents the control as whole.
example: MyListView.LabelEdit = True
    Columns A collection that holds the columns of the ListView control in report view
example: colcount = MyListView.Columns.Count
        Column Represents a column in report view
example1: MyListView.Column(2).Text = "Size (kbytes)"
example2: MyListView.Column("Size").Text = "Size (kbytes)"
            ColumnItems A collection of all the items/subitems in the column
example1: MyListView.Column(2).ColumnItems(5).Text = "20k"
example2: MyListView.Column(2)(5).Text = "20k"
    ListItems A collection of all the items (rows in report view) in the ListView
example: itmcount = MyListView.ListItems.Count
        ListItem Represent individual item (row in report view).
example1: MyListView.ListItems(5).Text = "Item 5"
example2: MyListView(5).Text = "Item 5"
example3: MyListView("MyItem5").Text = "Item 5"
            SubItems A collection of all the subitems of the item in report view
example: colcount = MyListView.ListItems(5).SubItems.Count
                SubItem Represents a subitem object in report view
example1: MyListView.ListItems(5).SubItems(2).Text = "20k"
example2: MyListView(5)(2).Text = "20k"
    Font The font settings for the control (apply to everything) (NSFont object)
example: MyListView.Font.Bold = True
    Icons List of the images used in Icon view (NSImageList object)
example: MyListView.Icons.LoadBitmap "\MyBitmap.bmp"
    SmallIcons List of the images used in SmallIcon and report view (NSImageList object)
example: MyListView.SmallIcons.LoadBitmap "\MyBitmap.bmp"
    ColumnHeaderIcons List of the images used in the column headings in report view (NSImageList object)
example: MyListView.ColumnHeaderIcons.LoadBitmap "\MyBitmap.bmp"

The NSListView object model diagram

Click on the object of interest to go to the page describing it.

NSListView general notes and remarks

The control's architecture may look complex at first, but in fact the usage of the control is quite simple. Each element is accessible through an object named after the element it represents thus enabling you to write code without checking the documentation for each line you write. To help you follow the naming convention the ListView terminology is listed below. The same terminology is used in MSDN and the documentation of other ListView ActiveX controls - if you have ever used one you will find it familiar.

Item - The ListView is a linear collection of items which consist of image, text, state, tag and other data (See also the views below)
Column - (visible in report view only) is a column which may have or not have a heading. The items and their subitems are listed in columns.
SubItem - (visible in report view only) each item may have subitems - one per each column currently visible in the control.
View - 4 views are supported by the control: Icons (sometimes referred as big icons), Small icons, List and Report. The Report view is the most complex one and offers grid-like functionality. NSListView is especially designed to simplify grid-like usage.

The views

Icon view (big icons).

The images from the Icons image list are used, the item text is displayed under the image. If checkboxes are enabled they appear on the left of the image.

Small Icons view

Much like the Icon view but the images from the SmallIcons image list are used and the item text is displayed on the right. If checkboxes are enabled the checkbox appears on the left side.

 

List view

Although similar to the Small Icons view in List view the items are listed sequentially in columns from left to right. The images from the SmallIcons image list are used.

Report view

The images from the SmallIcons image list are used. The items are listed vertically in the first column (unless the column order is changed by the application) and the other columns display the corresponding SubItem of the item. If you think of the items as rows you can think of the first column as of rows headers and for the SubItems as cells of a table.

All the Items, columns and SubItems can be accessed, changed and otherwise managed no matter the current view. However the columns and the sub items will be visible only in report view.

2. Objects reference

NSListView

Represents the NSListView control. Exposes general properties and the objects that control the internal elements of the control.

Members reference

Name Syntax Description
Objects
Columns Set cols = object.Columns Returns the Columns collection. It contains all the columns in the control.
alias: ColumnHeaders
ListItems Set items = object.ListItems Default. Returns the ListItems collection which contains all the items (ListItem objects) in the control.
Icons Set icons = object.Icons NSImageList containing the large icons, which are displayed with the items in the Icon view.
By default this image list is initialized with size 32x32
SmallIcons Set icons = object.SmallIcons NSImageList containing the small icons, which are displayed with the items in the all the views other than Icon view. The same list is also used when images are displayed with the sub-items.
By default this image list is initialized with size 16x16.
ColumnHeaderIcons Set icons = object.ColumnHeaderIcons NSImageList containing the icons, which are displayed on the column headers.
By default this image list is initialized with size 16x16.
Font Set fnt = object.Font Contains NSFont object that specifies the font used everywhere in the control.
View and behavior 
AllowColumnReorder object. AllowColumnReorder = b
b = object. AllowColumnReorder 
Enables (True)/Disables (False, default) the user to reorder the control's columns in report view by dragging them with the mouse or the stylus.
View object.View = v
v = object.View 
Puts/Gets the current view mode of the control:
0 - (default) Icon view (big icons)
1 - Report view
2 - Small icons view
3 - List view
HideSelection object. HideSelection = b
b = object. HideSelection
Boolean. Default is True. If set to false the selection in the control is indicated also when the control does not have the focus.
MultiSelect object.MultiSelect = b
b = object.MultiSelect 
Boolean. Default is True. When set to False only one item can be selected at a time.
Enabled object.Enabled = b
b = object.Enabled 
Enables/Disables the control.
Arrange object.Arrange = a
a = object.Arrange 
Integer constant. Specifies how to arrange the items in the control in Icon and Small Icons view only. Has no effect in the other view modes.
HideColumnHeaders object. HideColumnHeaders = b
b = object. HideColumnHeaders 
Boolean. Default is False. If set to True the column headings are hidden in report view.
LabelEdit object. LabelEdit = b
b = object. LabelEdit 
Boolean. Default is False. If set to True enables the user to invoke label editing for items by "slow" double click or pressing F2.
LabelWrap object.LabelWrap = b
b = object.LabelWrap 
Enable/disable the label text wrapping.
Checkboxes object.Checkboxes = b
b = object.Checkboxes
Enable/disable checkboxes view. If set to True the items are displayed with checkboxes beside them and the user can check/uncheck them. It works in all the views, but is most convenient in report view. In the other view modes the appearance may be a bit confusing for the users. See also the ListItem.Checked property.
FullRowSelect object.FullRowSelect = b
b = object.FullRowSelect
When set to True in report view the selection mark covers the entire row and not only the item. Often used together with GridLines (see below). 
SubItemImages object.SubItemImages = b
b = object.SubItemImages
When set to True the SubItem-s display images from the SmallIcons image list. See SubItem.Icon for more information.
SortHeaders object.SortHeaders = b
b = object. SortHeaders 
True by default. If set to False the headers cannot be clicked and do not fire events. If you want to indicate to the user that the control cannot be sorted use this when going to report view.
GridLines object.GridLines = b
b = object.GridLines 
When set to True grid lines are drawn between the rows and the columns. The effect is table like.
BackColor object.BackColor = clr
clr = object.BackColor
Sets/gets the background color of the control. Use the RGB function to create color values.
TextBackColor object.TextBackColor = clr
clr = object.TextBackColor
Sets/gets the background color of the texts in the control. Use the RGB function to create color values.
TextColor object.TextColor = clr
clr = object.TextColor
Sets/gets the color of the texts in the control. Use the RGB function to create color values.
TrackSelect object.TrackSelect = b
b = object. TrackSelect 
Desktop only, no effect on CE. The item under the mouse cursor is highlighted and if the cursor remains over it some time the item is selected.
UnderlineCold object.UnderlineCold = b
b = object.UnderlineCold
Desktop only, no effect on CE. The effect is like the link hover effect in IE.
UnderlineHot
Top object.Top = v
v = object.Top
Long integer. Puts/Gets the top coordinate of the control in the form.
Left object.Left = v
v = object.Left
Long integer. Puts/Gets the left coordinate of the control in the form.
Width object.Width = v
v = object.Width
Long integer. Puts/Gets the width of the control in the form.
Height object.Height = v
v = object.Height
Long integer. Puts/Gets the height of the control in the form.
Visible object.Visible = b
b = object.Visible
Boolean. Gets/puts the visibility flag for the control. Default is True - visible.
Operations, sorting and so on
FindItems Set results = object.FindItems( _
    text, _
    [subitems], _
    [tags], _
    [partial])
Searches through the items and (optionally) the sub-items in the control. Returns a collection of the items and sub-tiems that match the criteria.
Arguments:
text - String. Text to search
subitems - (optional) Boolean. If True both the items and the sub-tiems are searched, default is False
tags - (optional) Boolean. If set to True the search is over the value of the item's/sub-item's Tag property and not the Text property. Default is False.
partial - (optional) constant:
    0 - (default) exact match
    1 - partial (match if the string starts with the searched text)
    2 - substring (match if the searched text can be found somewhere in the value)

Returns: a Results collection containing the ListItem and SubItem objects that match the criteria.

UnSelectAll object.UnSelectAll De-selects all the items in the control.
SelectedItems Set results = object.SelectedItems Returns a Results collection containing all the currently selected items (ListItem objects)
SetFocus object.SetFocus Sets the keyboard focus to the control. Aside of the obvious usage you may need to call this method when you use on your form a control that gets the focus implicitly after certain operation.    
SortOrder object.SortOrder = v
v = object.SortOrder 
Integer constant. Specifies the sort order in the control:
0 - (default) ascending
1 - descending
Assigning a value (even reassigning the same) causes resort. 
Sorted object.Sorted = b
b = object.Sorted 
When set to True the control is sorted in report view according to the other sorting settings (See SortOrder, SortKey and Column.SortType). Setting the property to True invokes re-sort of the entire control, this can be used when you want to invoke re-sort the control after changing some data in it.
SortKey   Integer between 0 and Columns.Count. Specifies the column on which the sorting will be performed. 
Tag object.Tag = v
Set object.Tag = v
v = object.Tag
Set v = object.Tag
Enables the application to attach a tag to the object.
Events
All the events fired by the control have the same syntax:
Sub NSListViewX_<EventName>(oEvent)
  ' Handle the event, use oEvent to access the event data.
End Sub
The oEvent above is an NSListViewEvent object
OnColumnClick Sub NSListViewX_<EventName>(oEvent)
  ' Handle the event, 
  ' use oEvent to access the event data.
End Sub
Fired when a column header is clicked. oEvent.Column is the Column clicked. 
OnBeginLabelEdit Fired when the user starts editing an items text label. The ListItem being edited is oEvent.Item. Also oEvent.Column contains reference to Column 0. By setting the oEvent.Cancel = True the editing can be refused
OnEndLabelEdit Fired when the user finishes editing an items label. The item being edited is oEvent.Item. Also oEvent.Column contains reference to Column 0. The oEvent.Text contains the text just entered by the user. By setting the oEvent.Cancel = True the text change is cancelled and the old text remains. 
OnItemActivate Fired when an item is activated. This is when the item is double-clicked, Enter key is pressed while the item has the focus. The item (ListItem) being activated is oEvent.Item. If the activation is a result of a mouse/tap action oEvent.SubItem contains the SubItem which has been double-clicked for example. Also oEvent.Column contains reference to the corresponding Column.
OnKeyDown Fired when a keyboard key is pressed in the control. The oEvent.Key contains the key's virtual code.
OnMarqueeBegin Fired when when the user starts selecting items by dragging a rectangle with the mouse/stylus. By setting the oEvent.Cancel = True the action can be cancelled. 
OnClick Fired when the left mouse button is clicked or when the user taps the touch screen. The oEvent's Item, Column and SubItem properties may contain references to the related objects. If an item (ListItem) is clicked the SubItem property contains nothing, if a SubItem is clicked the SubItem property contains the clicked SubItem. The Column property contains the Column in which the clicked Item or SubItem is.
OnDblClick Like OnClick, but fired on double click.
OnRClick Like OnClick but fired on right mouse button click.
OnRDblClick Like OnClick but fired on right mouse button double-click.
OnReturn Fired when the Return key is pressed. No useful information is available in oEvent object.
OnItemChanged Fired when the state of an item changes. Any change will cause this event to occur. Use oEvent.Item to query the ListItem's properties and determine what the change might be and if it is of any interest

 

ListItems collection

A collection that contains all the items (ListItem objects) in the control

Syntax:

NSListView.ListItems

Members reference

Name Syntax Description
Methods and properties
Add [Set itm =] object.Add(
    [Index],
    [Key],
    [Text],
    [Icon],
    [Indent])
Adds a new item (ListItem object) to the control. All the arguments are optional, they are:
Index - integer specifying the index for the new item 1 - based. If omitted the item is added as last item.
Key - String, the key name for the item. If specified the created ListItem object can be accessed later by name.
Text - The text label for the new item.
Icon - Image index or name in the image list applicable to the current view (Icons in Icon view, SmallIcons in all the other cases). 
Indent - Specifies the indent of the item in report view. See ListItem.Indent
Clear object.Clear Removes all the items.
Count c = object.Count Integer. Returns the count of the items.
Item Set itm = object.Item(x)
Set itm = object(x)
Default. Returns the indexed item (ListItem object).
x - is integer 1-based index or Key name of an item. If more than one item has the same Key the first is returned.
Remove object.Remove x Removes the indexed item (ListItem object) from the control.
x - is integer 1-based index or Key name of an item. If more than one item has the same Key the first is removed.
Enumerator For Each o in object
Next
Enumerates the elements of the collection.
Hierarchy members
ListView Set NSListView = object.ListView Returns reference to the NSListView control to which this object applies

 

ListItem object

Represents an item in the control. In all the view modes except report view the items is all that is shown in the control. In report view the item (ListItem) plays a role very similar to a row in a grid. Its sub-items (see the SubItems collection) can be considered like the cells in the row, while the item itself is the cell 0 or the heading cell of the row. 

Syntax:

Set itm = NSListView.ListItems.Item(index)
or
Set itm = NSListView.ListItems(index)
or
Set itm = NSListView(index)
or
Set itm = NSListView("key")
or
For Each itm In NSListView.ListItems
   ' make use of itm
Next

 

Members reference

Name Syntax Description
Objects
SubItems Set si = object.SubItems Default. Returns the SubItems collection which enables you to edit the sub-items of this item/row.
Methods and properties
EnsureVisible object.EnsureVisible [partial] Makes sure that the item is visible. Scrolls the contents of the control as needed. If partial is not omitted and set to True the item is considered visible even if only part of it is in the visible area of the control. Note!  This sets the focus to the control. 
StartLabelEdit object.StartLabelEdit Initiates interactive label editing of the label of this item. Has no effect if the NSListView's LabelEdit property is False.
Checked object.Checked = bval
b = object.Checked 
Gets/sets the checked state of the item. Should be used only in checkboxes mode (see NSListView.Checkboxes property). If Checkboxes is False the result is undefined.
Icon object.Icon = icn
icn = object.Icon
Sets/returns the icon index for the item. The index corresponds to an image in the image list applicable for the current view mode.  When set (object.Icon = icn) you can use both numeric index and key name of an image in the image list. When queried numeric index is always returned.
Index i = object.Index Returns the index of the item in the control. This is the same index as in the ListItems collection.
Key object.Key = key_name
v = object.Key 
Sets/gets the key name of the item. This name can be used instead of numeric index to access the item in the ListItems collection. It is not required to specify unique name, but if the name is not unique the first found item with the given key name is returned (see ListItems collection).
Selected object.Selected = bval
b = object.Selected 
Sets/gets the selected state of the item. See also NSListView.SelectedItems.
Tag object.Tag = v
Set object.Tag = v
v = object.Tag
Set v = object.Tag
Enables the application to attach a tag to the object. It can be used also by the sorting and find methods.
Indent object.Indent = n
n = object.Indent 
Sets/gets the indent of the item in report view only. The value specifies image widths, thus small values should be used. Even if you are not using images, adjust the image size in the SmallIcons image list in order to specify what equals to indent=1 (i.e. indent=1 shows the item 1 image widths to the right). 
Text object.Text = str
str = object.Text
Sets/gets the item text.
X object.X = v
v = object.X 
Sets/gets the items's position in the list view in Icons and Small icons view. Using these two properties you can move the item, arrange manually the items to reflect some kind of grouping etc.
Y object.Y = v
v = object.Y 
Hierarchy members
ListItem Set o = object.ListItem Returns a reference to self. As the SubItem object has the same property (which returns the item to which the sub-item belongs) this property can be used in pieces of code where the items and the sub-items are not distinguished from each other. 
IsSubItem b = object.IsSubItem For the ListItem object always returns False.
ListView Set o = object.ListView Returns a reference to the NSListView object to which this item belongs.

 

Columns collection

A collection that contains all the Column objects in the control. Note that the column 0 always exists and cannot be deleted. It can be only changed. Thus the control starts with one column in which the items are listed in report view. All the collections in this control are 1-based, the column 0 is the only exception. To make it more natural the Columns collection behaves as all the other collections in the control if you consider only the explicitly added columns (see the Add method below). Still, in contrast to the other collections it allows usage of index = 0 to which the static column 0 corresponds.

Syntax:

NSListView.Columns
or
NSListView.ColumnHeaders

 

Members reference

Name Syntax Description
Methods and properties
Add [Set col =] object.Add (_
  [index], _
  [Key], _
  [Text], _
  [Width], _
  [Alignment], _
  [Icon])
Adds/inserts a new column in the control. All the parameters are optional and can be modified later through the Column object's properties. There is only one specific exception: if the Icon is not set when the column is created using this method, the column will not support images and any later attempts to set an icon to it will have no effect (see the notes in the Using NSListView control section about why this behavior is left as it is in the underlying windows control).
The arguments:
Index - the index at which the column will be placed. If omitted the column is appended to the existing columns.
Key -  Key name for the column. It can be used in the Columns collection to access the column instead of numeric index.
Text - Initial text for the column header
Width - Initial column width. If omitted 50 pixels is the default width.
Alignment - Initial alignment of the text and the image in the column header. See the Column.Alignment for details about the possible values.
Icon - The icon index or key name from the ColumnHeaderIcons image list (See the note above).
Clear object.Clear Removes all the columns.
Count c = object.Count Returns the number of the columns in the control, not counting the column 0. Because of this behavior you can use For ... Next cycles as with the other collections from 1 to Count when enumerating the columns you added and from 0 to Count if you want to enumerate also the column 0.
Item Set col = object.Item(x)
Set col = object(x)
Default. Returns the column specified by x. X can be integer index from 0 to Count or key name. If the key name is not unique the first column with that Key name is returned.
Remove object.Remove x Removes the column specified by x. X can be integer index from 1 to Count or key name. If the key name is not unique the first column with that Key name is returned. The column 0 cannot be removed.
Enumerator For Each o in object
Next
Enumerates the elements of the collection.
Hierarchy members
ListView Set lv = object.ListView Return a reference to the NSListView control to which this object belongs.

 

Column object

Represents a particular column in the control.

Syntax:

Set col = NSListView.Columns(index)
or
Set col = NSListView.ColumnHeaders(index)
or
Set col = NSListView.Columns("key")
or
Set col = NSListView.ColumnHeaders("key")
or
For Each col In NSListView.Columns
   ' make use of col
Next

 

Members reference

Name Syntax Description
Objects and collections
ColumnItems Set o = object.ColumnItems A collection of all the items or subitems in the column. If this is column 0 the elements are Item objects, if this is column 1 or greater the elements are SubItem objects.
Properties and methods
Alignment object.Alignment = c
c = object.Alignment 
Sets/Gets the text alignment in the column. The allowed values are:
0 - NSLVColumnLeft - left aligned (default).
1 - NSLVColumnRight - right aligned.
2 - NSLVColumnCenter - centered.
Icon object.Icon = icn
icn = object.Icon 
Sets/gets the image index which is to be displayed in the column header from the ColumnHeaderIcons image list. icn is  1-based image index in the image list or (when assigned only) it can be also the image's key name in the image list. 
Index idx = object.Index Returns the column index.
Key object.Key = key_name
key_name = object.Key
Sets gets the key name of the column. This name can be used later to access the column through the Columns collection. Furthermore the same key name can be used to access the sub-items in that column through the ListItem.SubItems collection.
Position object.Position = pos
pos = object.Position
Sets/gets the visual order position of the column. This value should be in the same range as the column indices. However, changing the column position does not affect its index. I.e. the visual order of the columns can be different from the internal order.
SortType object.SortType = v
v = object.SortType 
Defines how the sorting will be done when and if the NSListView.SortKey is set to the index of this column. The possible values are:
0 - Sort as texts by the content of the ListItem/SubItem Text property
1 - Sort as numbers by the content of the ListItem/SubItem Text property
2 - Sort as texts by the content of the ListItem/SubItem Tag property
3 - Sort as numbers by the content of the ListItem/SubItem Tag property
When sorted as numbers the text or the tag of the items/sub-items in the column is converted to double precision number and then complared.
Using values of 2 and 3 enables you to show visually one data, but sort the items by another data kept in their Tag properties. This is especially useful when you need to format the visually displayed data in user friendly manner which is not good for sorting - for example "100kg" is not a number and worse you may have the values rounded to different scales "100kg", "1.2t" etc. Keeping a clean value in the Tag property solves the problem.
Tag object.Tag = v
Set object.Tag = v
v = object.Tag
Set v = object.Tag
Enables the application to attach a tag to the object. It can be used also by the sorting and find methods.
Text object.Text = str
str = object.Text
Sets/gets the column caption text
ShowImage object.ShowImage = b
b = object.ShowImage
Specifies if the column shows an image from the ColumnHeaderIcons image list in its header. If an icon is specified when the Columns.Add creates the column or later an image index is assigned to the Icon property this property is set automatically to True. If you want to hide the image in a given column you can set ShowImage to False and back to Ture when you want to show the image again.
Hierarchy properties
ListView Set lv = object.ListView Return a reference to the NSListView control to which this object belongs.

 

ColumnItems collection

A collection that contains all the ListItem or SubItem objects in the Column to which this object belongs

Syntax:

NSListView.Columns(index).ColumnItems

Members reference

Name Syntax Description
Methods and properties
Count c = object.Count Returns the number of "rows". Actually this property returns the number of items in the control because in report view the number of the rows is equal to the number of the items in the control. Thus this value is the same as the value returned by NSListView.ListItems.Count
Item Set itm = object.Item(x)
Set itm = object(x)
Returns the indexed item or sub-item. Depending on the column to which this object belongs the object returned will be ListItem (for column 0) or SubItem for any other column.  
Enumerator For Each itm In object
Next
Cycles through all the existing sub-items in the column. Note that the sub-items that have never been set are skipped. I.e. the cycle will enumerate objects <= Count. Thus this syntax is good when you want to enumerate all the non-empty "cells".

 

SubItems collection

A collection that contains all the SubItem objects of the Item to which this object belongs.

Syntax:

NSListView.ListItems.Item(index).SubItems
or
NSListView(index).SubItems

Members reference

Name Syntax Description
Methods and properties
Clear object.Clear Removes all the sub-items of this item.
Count c = object.Count Returns the number of the sub-items of the item. This is always equal to the number of the Columns (without column 0).
Item Set o = object.Item(x)
Set o = object(x)
Default. Returns the addressed sub-item. x can be an integer between 1 and Count or a key name of the Column containing the SubItem. Note that for efficiency the SubItem-s that have been never used are actually not created.
Remark: If you want to minimize the memory usage in an NSLitView control containing huge number of rows, but sparsely populated with sub-items avoid using For I = 1 to object.Count cycles over the SubItems collections and prefer For Each cycles. This way you will never invoke creation of objects that would eventually remain empty.
Remove object.Remove x Removes the SubItem addressed by x which can be an integer between 1 and Count or a key name of the column in which the sub-item is.
Enumerator For Each o in object
Next
Enumerates the elements of the collection.
Hierarchy members
ListItem Set itm = object.ListItem Returns a reference to the ListItem to which this collection belongs.
ListView Set lv = object.ListView Return a reference to the NSListView control to which this object belongs.
Internal members
These members are documented but it is recommended to not use them. They exist to support certain internal features of the control.
DefinedCount c = object.Count Returns the count of the existing sub-items. I.e. the SubItem objects that are currently maintained by the collection and not the number of the columns.
ItemByIndex Set sitm = object.ItemByIndex(x) Returns a SubItem by its internal index. This index does not correspond to its visual position.
RemoveByIndex object.RemoveByIndex(x) Removes a SubItem by its internal index. This index does not correspond to its visual position.

 

SubItem object

Represents a sub item in the control.

Syntax:

Set subitm = NSListView.ListItems.Item(index).SubItems(subindex)
or
Set subitm = NSListView.ListItems.Item(index)(subindex)
or
Set subitm = NSListView(index)(subindex)
or
Set subitm = NSListView.ListItems(index).SubItems(subindex)
or
Set subitm = NSListView(index).SubItems(subindex)
or
Set subitm = NSListView.ListItems(index)(subindex)
or
For Each subitm In NSListView(index).SubItems
   ' make use of subitm
Next
or
For Each subitm In NSListView.Columns(index).ColumnItems
   ' make use of subitm
Next

 

Members reference

Name Syntax Description
Methods and properties
Icon object.Icon = icn
icn = object.Icon 
Sets/gets the image associated with the SubItem. The icn is an index from the SmallIcons image list. When assigned an image key name in the SmallIcons image list can be used instead of an index. Note that images are shown with the SubItems only if NSListView.SubItemImages is set to True.
Index idx = object.Index Returns the index of the object in the collection to which it belongs (see SubItems)
Key key = object.Key Gets the key name of the column to which the SubItem belongs. The SubItem can be addressed in the SubItems collection by this name as well as by its column index. 
Tag object.Tag = v
Set object.Tag = v
v = object.Tag
Set v = object.Tag
Enables the application to attach a tag to the object. It can be used also by the sorting and find methods.
Text object.Text = str
str = object.Text
Sets/gets the SubItem's text
Hierarchy members
IsSubItem b = object.IsSubItem Both ListItem and SubItem objects have this property. For SubItem objects it always returns True while for ListItem objects it always returns False. Sometimes the applications need to work with both ListItems and SubItems as if they are the same, still at some point it may be necessary to distinguish the ListItems from the SubItems - this property enables the application do it without need to query other information. For example this may happen if you use NSListView.FindItems method to search through the control. 
ListItem Set itm = object.ListItem Returns a reference to the ListItem to which this SubItem belongs.
ListView Set lv = object.ListView Return a reference to the NSListView control to which this object belongs.

 

Results collection

Represents a collection of objects returned as result of a search or other operation. The type of the objects in the collection depends on the operation.

Syntax:

Set result = NSBImageList.FindItems("search what",True)
or
Set result = NSBImageList.SelectedItems

Members reference

Name Syntax Description
Methods and properties
Count c = object.Count Returns the number of the elements in the collection. 
Item Set itm = object.Item(Index) Default, indexed property. Index is 1 based integer index.
Enumerator For Each itm in object
...
Next
Cycles through all the elements of the collection. 

 

NSListViewEvent object

Represents the event details. Each event fired by the control provides this object to the event handling routine. Depending on the event some or all of the members of the object may contain information. For example the OnClick event in report view may contain Column, Item and SubItem objects. These will be the SubItem over which the user has clicked, the item to which this SubItem belongs and the Column in which the SubItem is. Thus, the members of the object will always contain references to all the objects related to the event. As there can be only one object of each type related to a particular event there is one member for each type of the control elements.   

See also the Events list for information when each event occurs.

Syntax:

Sub NSListView_Ob<EventName>(oEvent)
  Set itm = oEvent.Item
  oEvent.Column.Text = "new caption"
  .....
End Sub

Members reference

Name Syntax Description
Methods and properties
Column Set c = object.Column Returns a reference to the Column related to the event if any..
Is/Can be non-empty for:
OnColumnClick,
OnBeginLabelEdit,
OnEndLabelEdit,
OnItemActivate,
OnClick,
OnDblClick,
OnRClick,
OnRDblClick,
OnItemChanged
Item Set itm = object.Item Returns a reference to the ListItem related to the event if any..
Is/Can be non-empty for:
OnBeginLabelEdit,
OnEndLabelEdit,
OnItemActivate,
OnClick,
OnDblClick,
OnRClick,
OnRDblClick,
OnItemChanged
SubItem Set sitm = object.SubItem Returns a reference to the SubItem related to the event if any..
Is/Can be non-empty for:
OnItemActivate,
OnClick,
OnDblClick,
OnRClick,
OnRDblClick,
OnItemChanged
Text s = object.Text Returns the text related to the OnEndLabelEdit event. This is the new text entered by the user.
Key n = object.Key Returns the virtual key code of the keyboard key pressed for the OnKeyDown event.
ListView Set lv = object.ListView Returns a reference to the ListView control that fired the event.
Event c = object.Event Returns integer constant corresponding to the event. Can be used if you are using a combined event handling routine called to handle more than one type of event.
Cancel object.Cancel = b Enables the event handler to cancel the action that caused the event. Only the OnMarqueeBegin, OnBeginLabelEdit and OnEndLabelEdit events can be cancelled.

Remarks:

The event handling code often needs to check it one of the Item, SubItem and Column properties of the event object are not empty and contain a reference to an object related to the event. This is usually done this way:

Sub NSListView_OnClick(oEvent)
  If Not oEvent.Item Is Nothing Then
    ' There is an ListItem object related to the event. 
  End If
End Sub

 

 

3. Using NSListView ActiveX control

The NS BASIC ListView control is easy to use despite the number of the objects in it. Their actual purpose is to represent each element in the control i a convenient way and thus enable you work with it in intuitive way. 

The ListView is a control that can be used in various ways - it can present simple pictured list of items with text labels, but it can also work like a table/grid and display data in columns with sorting and other extras. Furthermore the control can expose all the items in it as checkboxes, the items (in report/grid view) can be indented and the control may become quite similar to a tree view. All this makes it the control of choice for many tasks. Depending on the application the control can be pre-configured for a certain view only (e.g. as a grid or as icon view), but sometimes it is convenient to enable the user to change between 2 or more views. The classic example is the Windows Explorer in which the files can be viewed as big/small icons or in a report view with detailed information about the file in each row.

So, where to begin? We will begin with a simple icon view in mind, but we will then move to a report view. One of the most important features of the control is that all the elements are accessible and creatable no matter if the current view shows them or not. For example you can perform tasks that will fill information for the report view while the list is shown as icons - the data you add in the sub items will not be visible until the view is changed to report. This means that the application can always assume that the control is in report/grid view and manage its contents in this manner. So, if the task the application is performing deserves a report view you can think in its terms no matter if it is allowed to change the way the user views the data (thus hiding/unhiding parts of it when the view is changed).

Lets start: We assume we have a form (Form1) and a NSListView control is added to it under the name NSListView1 (see how to add the control to the toolbox). 

Let's add a few items for a start:

NSListView1.ListItems.Add 1,"Item1 Key","My item 1"
NSListView1.ListItems.Add 2,"Item2 Key","My item 2"
NSListView1.ListItems.Add , ,"My item 3"

We add the items through the ListItems collection. The control has many elements and that is why we need to be specific (For example we may add also columns or images).

All the arguments of the ListItems.Add method are optional, thus (in the 3-d line above) we decided to omit most of the item parameters. This is what the control will look like after these lines
:

There are no icons? Well, lets load some:

NSListView1.Icons.LoadBitmap "bigicons1.bmp"
' note that you may need to specify the full path to the bitmap in the real world

By default the items use the first icon from the loaded image. The image we loaded above actually looks like this:

The image list is a collection of images all with the same size. When a bitmap is loaded it expects there 1 or more images of the size currently configured. The images are to be ordered from left to right in the bitmap. By default the Icons image list is configured for 32x32 pixel images.

Now lets change the item images:
NSListView1.ListItems("Item1 Key").Icon = 1
NSListView1.ListItems("Item2 Key").Icon = 2
NSListView1.ListItems(3).Icon = 3

Above we have set keys for some of the items. This means that we can do the same this way:

NSListView1.ListItems(1).Icon = 1
NSListView1.ListItems(2).Icon = 2
NSListView1.ListItems(3).Icon = 3

So, the keys can be used as item name which can be specified instead of an index. This can be quite useful when the data in the control has no definite order.

Let's now do all this again, but  in much simpler way - saving some typing work:

NSListView1.Icons.LoadBitmap "bigicons1.bmp"
Set itm = NSListView1.ListItems.Add(1,"Item1 Key","My item 1")
itm.Icon = 1
Set itm = NSListView1.ListItems.Add(2,"Item2 Key","My item 2")
itm.Icon = 2
Set itm = NSListView1.ListItems.Add( , ,"My item 3")
itm.Icon = 3

The Add method returns the just created item, thus giving us chance to do something more with its properties. We can also use the rest of the optional parameters of the Add method and eliminate the need to specify the item's image on a separate line:

NSListView1.ListItems.Add 1,"Item1 Key","My item 1", 1
NSListView1.ListItems.Add 2,"Item2 Key","My item 2", 2
NSListView1.ListItems.Add , ,"My item 3", 3
NSListView1.Icons.LoadBitmap "bigicons1.bmp"

Let's talk about line 3. It does not specify an index for the created item - where it will be put? The answer is it will be appended at the end of the ListItems collection. Thus skipping the index is equivalent to:

NSListView1.ListItems.Add NSListView1.ListItems.Count, ,"My item 3", 3

Therefore when we add the items sequentially or the order does not matter to the application we can just skip the index.

Now suppose we want to cycle through all the items and extract some information from them. For the example we will use their Text property. We can do this in two ways:

' Normal cycle
For I = 1 to NSListView1.ListItems.Count
  MsgBox NSListView1.ListItems(I).Text
Next

or

' Enumeration
For Each I In NSListView1.ListItems
  MsgBox I.Text
Next

Which way is better? Actually neither is better than the other, the latter needs a bit less code, but aside of that all depends on any other needs that you may have. The second technique is called enumeration. The control exposes enumerations in many places - for the items, for the columns, for the sub items of each item, for the items/sub items in each column and so on. Generally the enumeration is more effective especially if you enumerate sub items (discussed below).

Before continue let's change the view. Firs to small icons:

NSListView1.View = 2

Again no icons, what are we missing? All the other views except Icon view use the SmallIcons image list. We have nothing loaded in it yet, so no icons appear in the control. Let's load another bitmap - with smaller images (16x16 by default):

NSListView1.SmallIcons.LoadBitmap "smallicons1.bmp"

the bitmap looks like this:

and the control after the above line:

Now let's switch to report view and see what we can do with the control in its most powerful form.

NSListView1.View = 1

What we see? There is one column with empty caption and all the items are listed one under another in it. The SmallIcons are used. Can we put some caption to that column? Yes:

NSListView1.Columns(0).Text = "Items"

We can also set an icon to that column:

NSListView1.Columns(0).Icon = 1

But remember the columns have separate image list from which their icons are fetched and we have nothing in it yet. so to make the above two lines work we should:

NSListView1.ColumnHeaderIcons.LoadBitmap "smallicons1.bmp"
NSListView1.Columns(0).Icon = 1
NSListView1.Columns(0).Text = "Items"

By default the size of the header icons is 16x16 - the same as for the small icons, but you can change that (discussed later).

What is important about the report view? It looks like a table or let say a grid control. The NSListView is especially designed to make table-like usage convenient and natural. Now is the time to note some characteristics of the NSListView control. If you have some experience with other ListView controls or with the native Windows control (using C for example) it is very likely that you have some troubles especially if you have attempted dynamic changes of the columns and the items. NSListView hides virtually all the sensitive details and you can safely assume the report view a table/grid. To refine the table abstraction let say that the Items we discussed above play the role of rows and the columns are just columns. Thus the first column is special - it cannot be deleted, the items are listed in it, the column can be changed, but it is always present.

That's why the index of the first column is 0 while everything else in the control has 1-based indices. Furthermore the Columns.Count returns only the count of the columns you added without this first column which we will call later column 0. Thus the columns can be assumed to have 1-based indices if you count only the columns you can freely add and delete.

Let's add 3 columns:

NSListView1.Columns.Add , "Column1 Key","Column 1", 50
NSListView1.Columns.Add , "Column2 Key","Column 2", 50
NSListView1.Columns.Add , "Column3 Key","Column 3", 100, 2, 4

If we want to cycle through them we can do it like this:

For I = 1 To NSListView1.Columns.Count
  NSListView1.Columns(I).Text = "My Column " & I
Next

changing their caption text a little. As we said above this cycle will cycle only through the columns we added and will not include the fixed column 0. If we want to include it into the cycle we should change it:

For I = 0 To NSListView1.Columns.Count
  NSListView1.Columns(I).Text = "My Column " & I
Next

Now lets use enumeration instead of an index cycle:

For Each col In NSListView1.Columns
  col.Text = "Column " & col.Index
Next


We end up with something like this

Both cycles do the same work. When working with columns it is more likely that an index cycle will be better choice because for columns we will need more often to know the exact index. However, we shall see later that the enumerations are generally more convenient for almost everything else.

Back to the columns. The Columns.Add method has these parameters:
.Add index, Key, Text, Width, Alignment, Icon
All the arguments are optional, but you must be aware of the specific behavior of the columns about the icons. If no icon is specified when the column is created (added) no icon can be ever set to that column. This behavior of the native Windows control is preserved in the ActiveX for a reason - the icons even empty occupy some space. And this is the only way to get rid of that space. So, if the space in the column's caption is more precious than the opportunity to show icons in the column's header - omit the image argument, but remember that if you assign something to the Icon property of that column nothing will happen. To illustrate that lets cycle through the columns again and try to assign images:

For I = 0 To NSListView1.Columns.Count
  NSListView1.Columns(I).Icon = I - 1
Next

Nothing will change no matter that we actually have 4 icons with indices 1-4. If we change the code with which the columns have been created and specify some initial image the cycle will have effect.

What is the key for? Like with the items it can be used instead of the index:

Set mycolumn = NSListView1.Columns("Column2 Key")
will return the same as:
Set mycolumn = NSListView1.Columns(2)
because we keyed that column "Column2 Key"

Now let's do something with the "cells" of the table or in the terms of the list view - the sub items. Providing the columns are not reordered (see the Column.Position property) the column 0 (the left most one) contains the items which in the other view modes (icon, small icons and list) are the only visible elements in the work area of the control. To show something in the other columns we need to set some sub-items of some items. Lets do it randomly, because such a code will make use of many of the involved features:

Dim Itm, J, o
For Each Itm In NSListView1.ListItems
  Randomize
  J = Int(NSListView1.Columns.Count * Rnd) + 1
  Itm(J).Text = "SubItem " & J
  Itm(J).Icon = Int(4 * Rnd) + 1

Next

And the result will be something like this:

What the code does: It cycles through all the items in the control. Thinking of them as rows you can say it is a cycle through all the rows. For each row a random column is chosen, but never column 0 because it contains the items themselves. And through the item its subitems are accessed. The items are ListItem objects and their SubItems property gives us access to their sub-items which are SubItem objects. The SubItems property actually holds a SubItems collection object thus one of the highlighted lines above can be written this way:

Itm.SubItems.Item(J).Text = "SubItem " & J

However the SubItems is a default property of the ListItem object and the Item property of the SubItems collection is its default property and this enables us use the shorter syntax:

Itm(J).Text = "SubItem " & J

which exposes the item's sub-items as if they are its array elements. 

The NSListView attempts to expose the list view functionality in a way that enables you to work with it as with a grid. Of course you should remember that it is not a grid, but the resemblance is very close. So there is one more trick here - the ColumnItems collection. It enables us to access the items or the sub-items from a column. So lets go through all the columns (this time including the column 0 and access every item or sub-item in each column:

Dim c,I,J
For I = 0 to NSListView1.Columns.Count
  Set c = NSListView1.Columns(I)
  For J = 1 To NSListView1.ListItems.Count
    c.ColumnItems(J).Text = "Col=" & I & ".Row=" & J
  Next
Next

And the result will be pretty much:

Now, how to handle events? All the events fired by the control have the same syntax, for instance to handle the OnClick event you need a routine like this:

Sub NSListView1_OnClick(oEvent)
  ........
End Sub

All the events carry one argument - oEvent in the above example. The argument is not a simple value but an object - NSListViewEvent. The object has a few properties among which the Item, SubItem and Column are most interesting. Some or all of these 3 contain references to a ListItem object (Item property), SubItem object (SubItem property) and Column object (Column property). What means some or all then?

The different events concern different elements of the control. For example the user may have clicked an item or a sub-item. The event is the same - OnClick, but the objects causing it may be different. This applies to many of the other events. It is convenient to provide the event handling code with references to all the objects related to the event and thus free the code of the need to deduce them from minimal data (index for example). In the above OnClick event handler we can use:

oEvent.Column.Text = "Clicked !!!"

This line will change the caption of the column in which an item or sub-item has been clicked. As you can see the event handler does not need to deduce which column is this - it has a reference to it ready-to-use. Still, there is one more thing to be aware of - depending on the event and how exactly it has occurred the related objects may be different. For instance if an item has been clicked there is no relevant SubItem. Thus in an OnClick event handler that works with SubItem's it may happen that an item has been clicked and there is no relevant sub-item to the event. To find one of these 3 properties contains something one can use code like this:

If Not oEvent.SubItem Is Nothing Then
  ' There is a SubItem in this event - do something with it
End If

The same technique is used for any of these 3 properties.