In Visual Basic, the ListView control displays items in a collection. After adding the ListView item to your project, you can write functions to allow the user to edit items already in the list, insert new items to the list or take them out. You use the "Add" and "Remove" methods to perform these actions on list items, but Visual Basic allows you a lot of flexibility in how you implement these methods. One way is to call these methods when a user clicks a button.
Open your project's code window and add the following lines to the "Form_Load" function, or another function you call when your ListView control is activated:
ListView1.View = View.Details
ListView1.LabelEdit = True
ListView1.AllowColumnReorder = True
ListView1.GridLines = True
The View.Details function displays the ListView items. The LabelEdit function lets you edit text items in the ListView. AllowColumnReorder lets you rearrange the order of columns. GridLines displays a grid behind the ListView items, making them easier to see, especially when many items are in the list.
Open the "Design" editor. Double-click the "Button" control in the toolbox to add one to the form. Change the "text" property to "Add Item." Add a second button to the form, and change its "text" property to "Remove Item."
Open the "Add Item" button's "click" sub and type the following lines:
Dim item As New ListViewItem("Name")
The first line declares a new item to add to the ListView and enters "Name" into the first column. You can change this parameter to any other strings, including strings entered into TextBoxes. The second line contains data for the second column in the ListView. If your ListView has more columns, use an additional "item.SubItems.Add" for each one. The third line adds the item to the ListView list and displays it.
Open the "Remove Item" button's "click" sub and type the following line:
The "Remove" function removes an item from the ListView and takes a ListView item as a parameter. The parameter itself specifies the ListView item at index zero, otherwise the first item in the list, and removes it. You may write code to specify different items to remove, but make sure you include error handling in case the user tries to remove an item at an out-of-bounds index.
How to Use ListView With a CheckBox in VBA
Using a "ListView" control with check boxes in your Visual Basic for Applications (VBA) form can make your application more dynamic by...
Visual Basic ListView Tutorial
The ListView control in Visual Basic became popular with Windows Explorer. This control works in conjunction with the TreeView control and is...