Working with the ListView in VB.NET

Introduction

The inner-workings of a ListView can be somewhat complicated to grasp for an inexperienced programmer. The truth is, it is just a complicated control to fathom. All is not lost though, because once you know what makes a ListView tick, there is literally no project that you can think of not needing a Listview. It is very powerful, and very versatile, as you will see in today's article.

I also battled with the ListView in the beginning of my programming career, so do not feel alone! Today I will demonstrate practically how the ListView works, so sit back and relax, because it might end up being quite a lengthy article!

What Is a ListView?

The ListView is simply a list control that can also display images. If you look at normal list controls such as the ListBox and the Combobox, they can mainly show only text. Yes, you can include image functionality in either of them, but that is very complicated and not really part of this article. Another benefit of the ListView is that it has five different ways of presenting data. These are called view modes, which I will cover throughout this article. Here is a link to all the ListView's methods and properties. remember, when you do not know something, MSDN is the best place to look for information.

The ListView has one caveat: It works with an ImageList control. The ImageList control is simply (as its name implies) a list of images. It is an invisible control, in other words, you will not see it on the form during run time. Its sole purpose is to store a list of images, which can then be use with a ListView or picturebox, to name a few.

To get a better understanding of how the ListView works, let's create an application that makes use of ListViews.

Our Sample Project

Open Visual Studio and create a new Windows Forms VB.NET project. Design it to resemble Figure 1. The topic for this app is the 12 signs of the Zodiac. If you have never heard that term before, I suggest having a look here.

Our design
Figure 1 - Our design

In case Figure 1 is a bit confusing, put the following controls on your form and set the following properties :

Control Property Setting
ImageList Images Add any Large pictures. I have used the signs of the Zodiac. Try to make the pictures the same sizes.

List 1 - Large

ImageList Images Add any small pictures. I have used the signs of the Zodiac. Try to make the pictures the same sizes .

List 2 Small

ListView View LargeIcon
  LargeImageList ImageList1 - the Large Pictures
ListView View Details
ListyView View SmallIcon
  SmallImageList ImageList2 - the Small Pictures
ListView View List
ListView View Tiles
Button Text ListView1
Button Text ListView2
Button Text ListView3
Button Text ListView4
Button Text ListView5

We will use the buttons to show each ListView's content. If you do not have any pictures that you can use, I am including my pictures I have used both small and large versions of the Zodiac signs. Once you are happy with your design, we can proceed to the coding.

Code

In this program you will make use of arrays to store each zodiac sign, and each starting date and ending date. You will use these arrays to populate the desired ListView with data. Let's create the arrays now. Add the following code in the General Declaration section:

    Private arrZodiac(11) As String 'Array To Hold Zodiac Signs
    Private arrFrom(11) As String 'Each Zodiac Sign's Starting Date
    Private arrTo(11) As String 'Each Zodiac Sign's Ending Date

I mentioned 12 signs, now why are there only 11 elements? Well, it is because arrays start counting at 0.

In order to make these arrays work, we have to give them some data. The optimal place to add elements to each of these three arrays would be the Form Load event. Double click on the form - this will open up the code window with your cursor placed inside the Form_Load event. Add the next code:

        'Popluate Zodiac Array
        arrZodiac(0) = "Aries"
        arrZodiac(1) = "Taurus"
        arrZodiac(2) = "Gemini"
        arrZodiac(3) = "Cancer"
        arrZodiac(4) = "Leo"
        arrZodiac(5) = "Virgo"
        arrZodiac(6) = "Libra"
        arrZodiac(7) = "Scorpio"
        arrZodiac(8) = "Sagittarius"
        arrZodiac(9) = "Capricorn"
        arrZodiac(10) = "Aquarius"
        arrZodiac(11) = "Pisces"

        'Popluate Starting Dates
        arrFrom(0) = "21 March"
        arrFrom(1) = "20 April"
        arrFrom(2) = "21 May"
        arrFrom(3) = "21 June"
        arrFrom(4) = "23 July"
        arrFrom(5) = "23 August"
        arrFrom(6) = "23 September"
        arrFrom(7) = "23 October"
        arrFrom(8) = "22 November"
        arrFrom(9) = "22 December"
        arrFrom(10) = "20 January"
        arrFrom(11) = "19 February"

        'Populate Ending Dates
        arrTo(0) = "19 April"
        arrTo(1) = "20 May"
        arrTo(2) = "20 June"
        arrTo(3) = "22 July"
        arrTo(4) = "22 August"
        arrTo(5) = "22 September"
        arrTo(6) = "22 October"
        arrTo(7) = "21 November"
        arrTo(8) = "21 December"
        arrTo(9) = "19 January"
        arrTo(10) = "18 February"
        arrTo(11) = "20 March"

You have to ensure that your arrays align with one another. For example: If you have three arrays technically containing data about the same subject, make sure that your array indexes are the same, as well as the elements at those indexes pertain to one another. In the code above, Aries was the first item in the Zodiac array, so for the two remaining arrays, their first elements should be Aries' starting and ending dates.

LargeIcon ListView

Now that we have the arrays in our program, let us add the code to make the first ListView work. Add the next code behind the button labelled 'ListView 1':

        'LargeIcons

        'Declare A Variable To Loop Through Array Items
        Dim i As Integer

        'Loop Through Zodiac Array
        For i = 0 To arrZodiac.Length - 1

            ListView1.Items.Add(arrZodiac(i)) 'Add Each Item Of Zodiac Array

            ListView1.Items(i).ImageIndex = i 'Align ImageList Images With Array Items

        Next

An easy one to start with. I declared a variable named i. This variable will be used as a loop counter in our For Loop. I start the For loop and indicate that the loop should start at 0 and end at the length of arrZodiac. In this case, it will give 12 ( because it does not start at 0 ) - that is why I put -1 at the end to give me 11. So, it means start looping from 0 and continues until 11.

I used the Add method of the ListView to add the arrZodiac element at position i. So, in this sense, i is just a placeholder for 0 to 11 whilst the loop is running. Lastly, still inside the loop, I connect the ImageList to the appropriate item, which is also at the same index.

If you were to run this application now, you will see the first ListView displaying large images as items.

LargeIcon ListView
Figure 2 - LargeIcon ListView

Have a quick break and a snack, because the next code that I will show you will be more difficult.

Details ListView

Add the following code for the 'ListView 2' button:

        'Details

        'Add Three Columns To ListView 2
        ListView2.Columns.Add("Zodiac", 100, HorizontalAlignment.Center) 'Column 1
        ListView2.Columns.Add("From", 100, HorizontalAlignment.Left) 'Column 2
        ListView2.Columns.Add("To", 100, HorizontalAlignment.Right) 'Column 3

        'Show Small Images Next To Zodiac Sign
        ListView2.SmallImageList = ImageList2

        'Declare Array For ListView Items
        Dim arrLVItem(11) As ListViewItem

        Dim j As Integer 'Loop Counter

        'Loop Through Each ListViewItem Array Item
        For j = 0 To arrLVItem.Length - 1

            'Initialize ListViewItem Array
            arrLVItem(j) = New ListViewItem

            'Add Text To First ListView Item - The Zodiac Sign
            arrLVItem(j).SubItems(0).Text = arrZodiac(j)

            'Add From and To SubItems On Zodiac ListView Item
            arrLVItem(j).SubItems.Add(arrFrom(j))
            arrLVItem(j).SubItems.Add(arrTo(j))

            'Connect ListView Item With Its Associated Picture
            arrLVItem(j).ImageIndex = j

        Next j

        'Add Completed Arrays To ListView
        ListView2.Items.AddRange(arrLVItem)

When a ListView's View property is set to Details, it is not only simple images you will be loading. here, you will deal with columns with optional images connected to them.

In the above code snippet, I first added three columns to the empty ListView. These columns each have a heading associated with it, and I specified each column's width and text alignment while creating it. I then connected the SmallImageList property to the ImageList containing all the small zodiac pictures. As usual, I opted to use a loop, hence the creation of the variable named j. I also created an array of type ListViewItem. This array will hold twelve elements and each element will represent a separate ListView item, and not Text only. A ListView Item is the whole item of the list. This List Item object can have sub items connected to it. Because there are three columns, the main item is the first item, whereas the remaining two columns each represent a sub item of the ListView item.

Inside the loop I instantiated the ListView Item array, and specified that the first column should display the Zodiac signs in text form. The next two columns are also populated with their respective array's data. In case you missed it, the second column is connected to the arrFrom array, and the third column is connected to the arrTo array. I then connected the images to each item, and added the item to the ListView.

There are many ways to work with a Details View ListView. I have always just favored this way, as it is quicker and more manageable from the coding point of view. Figure 3 shows this ListView in action.

Details ListView
Figure 3 - Details ListView

Please do not run away! The rest of the code I will demonstrate will not be as complicated as the above code.

SmallIcon ListView

Add the following code to the button labelled 'ListView 3':

        'SmallIcon

        Dim i As Integer 'Loop Counter

        'Loop Through Zodiac Array
        For i = 0 To arrZodiac.Length - 1

            ListView3.Items.Add(arrZodiac(i)) 'Add Each Zodiac Sign

            ListView3.Items(i).ImageIndex = i 'Connect Items With ImageList Picture Items

        Next

Nothing new here. You see, I told you it would not be complicated! Here, I basically employed the same logic as the logic inside 'ListView 1'. The only real difference is that this ListView is connected to the small ImageList. Run it, and it should resemble Figure 4.

SmallIcon ListView
Figure 4 - SmallIcon ListView

See the difference between LargeIcon and SmallIcon? Magnificent!

List ListView

Add the next code behind the button labelled 'ListView 4':

        'List

        'Use With Structure To Popluate ListView 4
        With ListView4

            .View = View.List 'Set View Mode

            .FullRowSelect = True 'Select Full Row

            .Columns.Clear() 'Clear Existing Columns
            .Items.Clear() 'Clear Existing Items

            Dim strZodiac As String 'String Object To Hold Zodiacs

            'For Each String In Zodiac Array
            For Each strZodiac In arrZodiac 'Loop Through Zodiac Array

                .Items.Add(strZodiac, 0) 'Add Items From Zodiac Array In Column 0

            Next

        End With

This looks entirely different than the other code segments I have shown. I decided it best to show you a broad spectrum of ways that you can employ to code a ListView, irrespective of its View mode. Here, I am using a With structure to set the ListView's properties. A With structure makes tedious coding a breeze as it takes out the name of the object and we can only specify the properties and their settings.

It should be self-explanatory, but allow me to explain further. The first real line of code opens the With structure. This identifies the object we will be using, in this case ListView4. On the next couple of lines we set ListView4's properties. Among the properties are: FullRowSelect, and View. Then we call a few of ListView4's built-in methods (Columns.Clear and Items.Clear that clears the columns and items from the ListView).

I then decided to use a different loop to add ListView4's items. Here, I have made use of a For Each loop instead of a For next Loop. The difference is that a For Next Loop uses a counter and loops a given number of times. A For Each loop can loop an unspecified amount of times as long as there is an item that resembles what you are looking for. Look closely, I have created a String object named strZodiac. Then, I loop through each of the arrZodiac array elements. So this, in layman's terms means: For each string inside the array arrZodiac, do the following (this would be what is between the For and Next lines). We add the items into the ListView in column 0 - which is the first column. Figure 5 shows this ListView in action.

List ListView
Figure 5 - List ListView

Tiles ListView

Add the code for the remaining button ('ListView 5 ):

        'Tiles

        ListView5.Columns.Clear() 'Clear Existing Columns
        ListView5.Items.Clear() 'Clear Existing Items

        'Add Columns
        ListView5.Columns.Add("Zodiac", 100, HorizontalAlignment.Center)
        ListView5.Columns.Add("From", 100, HorizontalAlignment.Left)

        Dim k As Integer 'Loop Counter

        For k = 0 To 11 'Loop Through Zodiac Array Items

            ListView5.Items.Add(arrZodiac(k)) 'Add Each Zodiac Array Item

            'Add From Sub Item For Each Zodiac Item
            ListView5.Items(k).SubItems.Add(arrFrom(k))

        Next k

With all that you have learned today, it should be easy to understand this last piece of code. You clear the columns and items from the ListView, so that it doesn't just simply add items indefinitely, but starts over every time the button is pressed. You then add Two columns to the ListView. Use a Loop to loop through your desired items and add them into their respective columns. Once run, your ListView will look like Figure 6.

Tiles ListView
Figure 6 - Tiles ListView

Conclusion

This was really fun! I hope you have enjoyed my article, and that you have learned from it. Until next time, cheers!



Related Articles

Downloads

Comments

  • Engineer

    Posted by shang on 09/18/2014 09:44am

    This article is very clear and well organizes. I enjoyed it a lot

    Reply
  • Errors

    Posted by Tonet on 09/02/2014 07:36am

    The system is running but the controls are not working, especially the buttons. What could be the solution or wrong with that?

    Reply
  • Just saying...

    Posted by tonet on 09/02/2014 04:32am

    thank you for this, I will try this codes

    Reply
Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Live Event Date: December 11, 2014 @ 1:00 p.m. ET / 10:00 a.m. PT Market pressures to move more quickly and develop innovative applications are forcing organizations to rethink how they develop and release applications. The combination of public clouds and physical back-end infrastructures are a means to get applications out faster. However, these hybrid solutions complicate DevOps adoption, with application delivery pipelines that span across complex hybrid cloud and non-cloud environments. Check out this …

  • On-demand Event Event Date: October 29, 2014 It's well understood how critical version control is for code. However, its importance to DevOps isn't always recognized. The 2014 DevOps Survey of Practice shows that one of the key predictors of DevOps success is putting all production environment artifacts into version control. In this webcast, Gene Kim discusses these survey findings and shares woeful tales of artifact management gone wrong! Gene also shares examples of how high-performing DevOps …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds