ListView (lsv)

microsoft excel docsListView (lsv) - Allows the user to select a single (or multiple) items from a list with multiple columns.

You can add new items to a listview by adding ListViewItem objects to the Items collection.


Examples

microsoft excel docs

Properties

ActivationWhether items are clickable with one or two clicks, the default being one click.
Alignment 
AllowColumnReorder 
AutoArrange 
CheckBoxesWhether the listbox displays checkboxes on the left of the first column (in List view).
CheckedIndices 
CheckedItems 
ColumnsThis is the collection of columns
Detailsthis is the mode that displays the column headers and subitems
Focusedreturns True if the control has the focus
FocusedItem 
FullRowSelectWhether the whole row is selected when an individual column is selected.
GridLines 
HeaderStyleGets or sets the column header style. Can be one of the following: none, nonclickable or clickable.
HideSelectionGets or sets a value indicating whether the selected item in the listview remains highlighted grey when the control loses focus.
HoverSelection 
Items 
LabelEdit 
LabelWrap 
LargeImageListlarge icon mode for the images in the image list
ListViewItemSorter 
MultiSelectWhether to allow multiple items to be selected.
OwnerDraw (Added 2.0) 
Scrollablecan be used to prevent scrolling
SelectedIndices 
SelectedItems 
SmallImageListsmall icon mode for the images in the image list
Sorting 
StateImageList 
Text 
TopItemGets the first visible item in the control.
ViewWhich view to display the items in either LargeIcon, Details, SmallIcon or List

Methods

ArrangeIconsArranges items in the control when they are displayed as icons.
BeginUpdatePrevents the control from drawing until the EndUpdate method is called.
ClearRemoves all the items and all the column headers from the control.
CreateObjRefCreates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object. (inherited from MarshalByRefObject)
DisposeReleases the resources used by the Component. (inherited from Component)
EndUpdateResumes drawing of the list view control after drawing is suspended by the BeginUpdate method.
EnsureVisibleEnsures that the specified item is visible within the control, scrolling the contents of the control if necessary.
GetItemAtRetrieves the item at the specified location.
GetItemRectRetrieves the bounding rectangle for an item within the control.
SortSorts the items of the list view.

Known Bugs

ListView.HideSelection = False

Visual Studio 2002
When this property equals False any manual changes to the backcolor of a listview are ignored.


The constructor for a ListViewItem can take a string (the caption for the icon) and an optional integer used as an index for the companion ListImage control.


Adding another item to an existing list

Dim objListViewItem As System.Windows.Forms.ListViewItem 
objListViewItem = New System.Windows.Forms.ListViewItem("some text", 0)
ListView1.Items.Add objListViewItem

Or Alternatively

Dim objListViewItem As System.Windows.Forms.ListViewItem 
objListViewItem = New System.Windows.Forms.ListViewItem()
objListViewItem.Text = "some text"
objListViewItem.ImageIndex = 0
ListView1.Items.Add objListViewItem


Inserting a new item at the beginning of the collection

Dim objListViewItem As System.Windows.Forms.ListViewItem 
objListViewItem = New System.Windows.Forms.ListViewItem("Another item", 0)
ListView1.Items.Insert(0, objListViewItem)

The Bounds property returns a Rectangle object that tells where the item is on the screen


Individual subitems have there own Text, Font, ForeColor and BackColor properties


Dim objFont As System.Drawing.Font 
objFont = New System.Drawing.Font

With objListViewItem.SubItems.Add("fourth column")
   .Font = New System.Drawing.Font.
   .ForeColor = System.Drawing.Color.Red
   .BackColor = System.Drawing.Color.Yellow
End With


What is a ListViewItem ?

This is the object that represents an item in a ListView control
The ListViewItem class defines the appearance, behavior, and data associated with an item that is displayed in the ListView control.


The ListViewItem constructor can take a string and an optional integer used as an index for the accompanying image.

Dim objListViewItem As System.Windows.Forms.ListViewItem 
objListViewItem = New System.Windows.Forms.ListViewItem("Item 1", 2).
Me.ListView.Items.Add(objListViewItem)

The properties window lets you add new ListViewItem objects and one or more subitems as well as all the ColumnHeader objects that you want to define


Properties

BackColorGets or sets the background color of the item's text.
BoundsGets the bounding rectangle of the item, including subitems.
CheckedGets or sets a value indicating whether the item is checked.
FocusedGets or sets a value indicating whether the item has focus within the ListView control.
FontGets or sets the font of the text displayed by the item.
ForeColorGets or sets the foreground color of the item's text.
GroupGets or sets the group to which the item is assigned.
ImageIndexGets or sets the index of the image that is displayed for the item.
ImageKeyGets or sets the key for the image that is displayed for the item.
ImageListGets the ImageList that contains the image displayed with the item.
IndentCountGets or sets the number of small image widths by which to indent the ListViewItem.
IndexGets the zero-based index of the item within the ListView control.
ListViewGets the ListView control that contains the item.
NameGets or sets the name associated with this ListViewItem.
PositionGets or sets the position of the upper-left corner of the ListViewItem.
SelectedGets or sets a value indicating whether the item is selected.
StateImageIndexGets or sets the index of the state image (an image such as a selected or cleared check box that indicates the state of the item) that is displayed for the item.
SubItemsGets a collection containing all subitems of the item.
TagGets or sets an object that contains data to associate with the item.
TextGets or sets the text of the item.
ToolTipTextGets or sets the text shown when the mouse pointer rests on the ListViewItem.
UseItemStyleForSubitemsGets or sets the value indicating if the Font, ForeColor, and BackColor properties for all the subitems should be the same as those for the for the item.

Methods

BeginEditPlaces the item text into edit mode.
CloneCreates an identical copy of the item.
EnsureVisibleEnsures that the item is visible within the control, scrolling the contents of the control, if necessary.
FindNearestItemFinds the next item from the ListViewItem, searching in the specified direction.
GetBoundsRetrieves the specified portion of the bounding rectangle for the item.
GetSubItemAtReturns the subitem of the ListViewItem at the specified coordinates.
RemoveRemoves the item from its associated ListView control.

What is a ColumnHeader ?

This is the object that represents a single column header in a Listview control.
A column header is an item in a ListView control that contains heading text.
ColumnHeader objects can be added to a ListView using the Add method of the ListView.ColumnHeaderCollection class.
To add a group of columns to a ListView, you can use the AddRange method of the ListView.ColumnHeaderCollection class.
You can use the Index property of the ColumnHeader class to determine where the ColumnHeader is located in the ListView.ColumnHeaderCollection.


Dim objColumnHeader As System.Windows.Forms.ColumnHeader 
objColumnHeader = New System.Windows.Forms.ColumnHeader
objColumnHeader.Text = "Article Title"
'minus 20 to remove the horizontal scrollbar
objColumnHeader.Width = Me.ListView1.Width - 20
Me.ListView1.Columns.Add(objColumnHeader)

You can also resize the column widths at design time.



Properties

ContainerGets the IContainer that contains the Component. (Inherited from Component.)
DisplayIndexGets the display order of the column relative to the currently displayed columns.
ImageIndexGets or sets the index of the image displayed in the ColumnHeader.
ImageKeyGets or sets the key of the image displayed in the column.
ImageListGets the image list associated with the ColumnHeader.
IndexGets the location with the ListView control's ListView.ColumnHeaderCollection of this column.
ListViewGets the ListView control the ColumnHeader is located in.
NameGets or sets the name of the ColumnHeader.
SiteGets or sets the ISite of the Component. (Inherited from Component.)
TagGets or sets an object that contains data to associate with the ColumnHeader.
TextGets or sets the text displayed in the column header.
TextAlignGets or sets the horizontal alignment of the text displayed in the ColumnHeader.
WidthGets or sets the width of the column.

Methods

AutoResizeResizes the width of the column as indicated by the resize style.
CloneCreates an identical copy of the current ColumnHeader that is not attached to any list view control.
DisposeReleases the resources used by the ColumnHeader.
ToStringReturns a string representation of this column header.

Events

AfterLabelEdit 
BeforeLabelEdit 
ColumnClick 
DrawItem (Added 2.0) 
ItemActivate 
ItemCheck 
ItemDrag 
ParentChanged 
SelectedIndexChangedOccurs when the SelectedIndices collection changes.
If the Ctrl key is not held down (only possible when MultiSelect = True) then this event is fired twice. First when the previous selection is cleared and then after the new selection has been made.
TextChanged 

SelectedIndexChanged

Private Sub lsvListView_SelectedIndexChanged(ByVal sender As System.Object, _ 
                                                   ByVal e As System.EventArgs) _
                                                   Handles lsvEmailHistoryListWide.SelectedIndexChanged

'this is needed when the "MultiSelect" property = False
   If lsvListView.SelectedItems.Count = 0 Then Exit Sub

End Sub


Adding Items

You must make sure the View property has been changed to Details otherwise the subitems will not appear.
Subitems are only visible in Details view and only if you have defined a sufficient number of ColumnHeader objects.
You can create subitems by using the Add method of the ListViewItem's SubItems collection
You must add the listviewitem first before any subitems can be added.

Dim objListViewItem As System.Windows.Forms.ListViewItem 
objListViewItem = New System.Windows.Forms.ListViewItem("Item 1").

Me.ListView.Items.Add(objListViewItem)

objListViewItem.SubItems.Add("Sub Item 1")
objListViewItem.SubItems.Add("Sub Item 2")
objListViewItem.SubItems.Add("Sub Item 3")

Inserting Items

It is also possible to insert items in a particular position

Dim objListViewItem As System.Windows.Forms.ListViewItem 
objListViewItem = Me.ListView.Items.Insert(0, "some text")

Retrieving SubItems

objListViewItem.SubItems(0).Text = "entry in the first column 
objListViewItem.SubItems(1).Text = "entry in the second column



Removing individual items

Dim objListViewItem As System.Windows.Forms.ListViewItem 
objListViewItem = New System.Windows.Forms.ListViewItem("Item 1").

Me.ListView.Items.Remove(objListViewItem)
Me.ListView.Items.Remove(1)

Removing all Items

ListView.Items.Clear 
ListView.ListViewItemCollection.Clear


Removing all Column Headers

ListView.Columns.Clear 
ListView.ColumnHeaderCollection.Clear


Removing both Items and Column Headers

ListView.Clear 


Single Selection

There is no SelectedIndex property of a listview but you can use the Selected property from a ListViewItem
The following selects the first item in the listview.

Me.ListView.Items(0).Selected = True 

Why is the Item not selected ?

Make sure that the listview has focus before you set the Selected property.




Multiple Selection

You can use the SelectedItems collection



The SelectedItems and SelectedIndices collections return the list of selected items



Editing Items

objListViewItem.Text = objListViewItem.SubItems(0).Text 

Dim objListViewItem As System.Windows.Forms.ListViewItem

objListViewItem = Me.ListView.Items.Add("some text").

'The first item in the listview is SubItem 0.
objListViewItem.SubItems(1).Text = "10"
objListViewItem.SubItems(2).Text = "20"



Formatting SubItems

Individual subitems can have their own Text, Font, ForeColor and BackColor

Dim objListViewItem As System.Windows.Forms.ListViewItem 
objListViewItem = Me.ListView.Items.Add("some text").

With objListViewItem.SubItems.Add("some text")
   .Text =
  .Font =
   .ForeColor =
   .BackColor =
End With


Dragging Between Lists

Another common scenario where drag and drop is expected (and highly appreciated) involves moving items from one list of items to another. Typically buttons are also available in this scenario, but they require two mouse clicks (select the item, click the button). Drag and drop is more efficient here, because it only requires a single motion (select and drag).
The ListBox control does not support dragging multiple items. Clicking the list invalidates the multiple selection.


To move multiple items back and forth between two lists


Add two ListView controls to a form.
Set the AllowDrop property of each ListView control to true.
Set the MultiSelect property of each ListView control to true.
Set the View property of each ListView control to List.

Private Sub ListView_ItemDrag(ByVal sender As Object, _ 
                              ByVal e As System.Windows.Forms.ItemDragEventArgs) , _
                              Handles ListView1.ItemDrag, ListView2.ItemDrag

    Dim myItem As ListViewItem
    Dim myItems(sender.SelectedItems.Count - 1) As ListViewItem
    Dim i As Integer = 0

' Loop though the SelectedItems collection for the source.
    For Each myItem In sender.SelectedItems
' Add the ListViewItem to the array of ListViewItems.
        myItems(i) = myItem
        i = i + 1
    Next
' Create a DataObject containg the array of ListViewItems.
    sender.DoDragDrop(New DataObject("System.Windows.Forms.ListViewItem()", myItems), DragDropEffects.Move)
    
End Sub

The ListView and TreeView controls have an ItemDrag event that facilitates dragging.
A single ItemDrag event handler covers both controls; they are listed in the Handles clause. The sender parameter represents whichever control is initiating the drag.
The ItemDrag code creates an array of the type ListViewItem and populates it by looping through the SelectedItems collection.


Private Sub ListView_DragEnter(ByVal sender As Object, _ 
                               ByVal e As System.Windows.Forms.DragEventArgs) _
                               Handles ListView1.DragEnter, ListView2.DragEnter

' Check for the custom DataFormat ListViewItem array.
    If e.Data.GetDataPresent("System.Windows.Forms.ListViewItem()") Then
        e.Effect = DragDropEffects.Move
    Else
        e.Effect = DragDropEffects.None
    End If
End Sub

Private Sub ListView_DragDrop(ByVal sender As Object, _ 
                              ByVal e As System.Windows.Forms.DragEventArgs) _
                              Handles ListView1.DragDrop, ListView2.DragDrop

    Dim myItem As ListViewItem
    Dim myItems() As ListViewItem = e.Data.GetData("System.Windows.Forms.ListViewItem()")
    Dim i As Integer = 0

    For Each myItem In myItems
' Add the item to the target list.
        sender.Items.Add(myItems(i).Text)
' Remove the item from the source list.
        If sender Is ListView1 Then
            ListView2.Items.Remove(ListView2.SelectedItems.Item(0))
        Else
            ListView1.Items.Remove(ListView1.SelectedItems.Item(0))
        End If
        i = i + 1
    Next
End Sub

Because the DataFormats class does not include a member of type ListViewItem, the data must be passed as a system Type instead. In the DoDragDrop method, a new DataObject is created and populated with the array. This same technique can be used to drag and drop any system Type.


In the DragDrop event, the array is copied from the DataObject into a new ListViewItem array, and each ListViewItem is added to the Items collection of the target ListView control.




Sorting

ListViewItemSorter Property

You can use this property to provide custom sorting, for example, when a column header is clicked in the details view.
First create a class that implements the IComparer interface and provides a constructor that accepts the index of a column to sort by.
This sorting will then be performed when you call the Sort method or when items are added to the list.
When you set the ListViewItemSorter property to the new instance, the ListView control is automatically sorted using the specified object.
Subsequent calls to the Sort method use the same object.
Note that items are not sorted automatically when their label text changes.


Add a ColumnClick Event Handler

Include the total number of columns and how you want each one to be sorted.

Private Sub lsvListView_ColumnClick 
   Private Sub lsvDatabase_ColumnClick(ByVal sender As Object, _
                                       ByVal e As System.Windows.Forms.ColumnClickEventArgs) _
                                       Handles lsvDatabase.ColumnClick

         Select Case e.Column
            Case 0 : Call clsListView.ColumnSort(lsvListView, "Number", e.Column)
            Case 1 : Call clsListView.ColumnSort(lsvListView, "String", e.Column)
            Case 2 : Call clsListView.ColumnSort(lsvListView, "String", e.Column)
            Case 3 : Call clsListView.ColumnSort(lsvListView, "Number", e.Column)
         End Select

   End Sub

ImageLists

LargeImageList - used for the images in Large Icon view
SmallImageList - used for the images in Small Icon, List and Details view




Files in a Folder

Public Shared FolderToListView(sFolderPath As String) 
   Dim objdirectoryinfo As System.IO.DirectoryInfo
   Dim objfileinfo As System.IO.FileInfo
   Dim objlistviewitem As System.Windows.Forms.ListViewItem

   objdirectoryinfo = New System.IO.DirectoryInfo(sFolderPath)

   Me.ListView.BeginUpdate
   For Each objfileinfo In objdirectoryinfo.GetFiles()

   objlistviewitem = Me.ListView.Items.Add(objfileinfo.Name).

   objlistviewitem.SubItems.Add(objfileinfo.Length)
   objlistviewitem.SubItems.Add(objfileinfo.CreationTime)
   objlistviewitem.SubItems.Add(objfileinfo.LastWriteTime)
   objlistviewitem.SubItems.Add(objfileinfo.LastAccessTime)

   Next objfileinfo

   Me.ListView.EndUpdate
End Sub




© 2024 Better Solutions Limited. All Rights Reserved. © 2024 Better Solutions Limited TopPrevNext