C# Windows Forms ListView and ArrayList

In this class we populate a ListView with an arraylist of data then handle the ItemSelectionChanged events for our ListView and show the selected item in a messagebox.

This is a practical tutorial for beginners and is meant to introduce you to both the ArrayList and ListView, and how to use them together. We will be creating this without using a designer so as to be responsible for everything hence learn more.

ArrayList seems to be the mostly used Collection while ListView may only be second to datagridview.

What is a ListView?

A ListView is a windows forms control that displays a collection of items that can be displayed using various views.
With a ListView you can display a list of items with text and images.

ListView can be created just by instantiating them:

            ListView myListView = new ListView { Location = new Point(30, 70), Size = new Size(400, 400), View = View.Details, FullRowSelect = true, Alignment = ListViewAlignment.SnapToGrid };

API Definition

ListView resides in the System.Windows.Forms namespace.

System.Windows.Forms resides in the System.Windows.Forms.dll assembly.

ListView class derives from System.Windows.Forms.Control namespace:

public class ListView : System.Windows.Forms.Control

That System.Windows.Forms.Control is a class that defines the base class for controls, which are components with visual representation.

ListView Items

ListView has an Items property which will allow us to add retrieve the items displayed by the control.

A single item is represented using the ListViewItem class.

This Items property allows us to access the ListView.ListViewItemCollection of the control. This in turn provides us with methods we can use to manipulate the items in the ListView.

For example here's how you can add items to a multicolumn ListView:

            foreach (string nebular in nebulae)
            {
                myListView.Items.Add(new ListViewItem(new[] { nebular, nebularCategory, nebularDistance }));
            }

ListView Selection

If you want to get the currently selected items you can use the SelectedItems property.

ListView allows user to select multiple items. For this you have to set the MultiSelect property to true.
On the other hand if you want to allow only a single item selection, then you set it to False.

Let's start.

What is ArrayList?

An ArrayList is basically a collection that Implements the IList interface and uses an array whose size is dynamically increased as required.

As you know the 'normal' array usually has a fixed size which has to be pre-defined either explicitly or determined implicitly based on the number of items specified.

However, with an arraylist size doesn't need to be defined and can automatically resized as more items are added.

An ArrayList resides in the System.Collections namespace and isn't generic.

ArrayList Add Items

To add items to an arraylist you can use the Add() method.

using System.Collections;

class Program
{
    static void Main()
    {
        ArrayList sages = new ArrayList();
        sages.Add("Buudha");
        sages.Add("Jesus");
        sages.Add("Mohamed");
        sages.Add("Krishna");

}

Iterating/Looping Through an ArrayList

You can use a foreach loop to iterate ArrayList items. Something like this:

        foreach (String sage in sages)
        {
            Console.WriteLine(sage);
        }
    }

Getting Number of Elements in ArrayList

You can use the Count property to retrieve the number of items in an arraylist. This property returns an integer.

        Console.WriteLine(sages.Count);

Clearing Items in an ArrayList

You can use the Clear() method to clear an arraylist of all its items.

        sages.Clear();

Sorting an ArrayList

System.Collections.ArrayList provides us with the Sort() method that allows us sort an arraylist, by default to ascending manner.

        sages.Sort();

Reversing an ArrayList

Once you've sorted the arraylist, you can reverse it to a descending manner using the Reverse() method. This method simply reverses the contents of an arraylist, be it sorted or not.

        sages.Reverse();

1. Create Empty Project

  1. Open up Visual Studio and proceed over to File --> New Project
  2. A new dialog popus up like this:
  1. Give our empty project a name and click OK. An empty project will get generated for us.

2. Make project a Windows Project

Just right click on your project choose properties and set output type to Windows Application:

3. Program.cs

Explanations

Specify Using Directives

We will add our imports via the using directive at the top of our namespace. This will import the namespaces our project will need.

using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

Define our Custom Namespace and Class

The namespace to host our class and the class itself.

namespace ListViewArrayList
{
    static class Program{..}
}

Create Form

We will have a method responsible for creating and displaying our form.

        private static void createForm()
        {
            Form myForm = new Form
            {
                Text = "WinForms ListView ArrayList Example - Camposha.info",
                ClientSize = new Size(564, 520),
                BackColor = Color.Tomato
            };

            myForm.Controls.Add(myListView);
            Application.EnableVisualStyles();
            Application.Run(myForm);
        }

As you can see first we instantiate the Form, set its Text, ClientSize and BackColor properties. Then add our ListView to its Controls property and finally Run() it.

Setup ListView.

We will setup our windows Forms ListView in this method:

        private static void setupListView()
        {
            myListView = new ListView { Location = new Point(30, 70), Size = new Size(400, 400), View = View.Details, FullRowSelect = true, Alignment = ListViewAlignment.SnapToGrid };
            myListView.Columns.Add("NAME", 100);
            myListView.Columns.Add("CATEGORY", 150);
            myListView.Columns.Add("DISTANCE(Light Years)", 150);

            myListView.ItemSelectionChanged += myListView_ItemSelectionChanged;
        }

First we have instantiated the ListView, specified its Location by assigning a System.Drawing.Point struct object and a Size object.

Furthermore we've specified the view type as View.Details. Because we want the whole row to be selected on selection we've specified FullRowSelect property to true.

Then we've added three columns to our ListView since we want to work with a mult-column ListView.

Lastly we've registered an event handler to our ListView's ItemSelectionChanged events.

Create our ListView ItemSelectionChanged Event handler

This event handler will handle the ItemSelectionChanged event, an event that gets raised when the user selects a given row in our ListView.

        static void myListView_ItemSelectionChanged(object sender, ListViewItemSelectionChangedEventArgs e)
        {
            if (e.IsSelected)
            {
                ListViewItem listViewItem = e.Item;
                MessageBox.Show(listViewItem.SubItems[0].Text);
            }
        }

In our case as you can see we are showing a messagebox with the selected item.

We are building a Community in our YouTube Channel

We have a YouTube Channel that is growing very fast. This is because we provide quality tutorials consistently. Moreover we attempt to answer questions from YouTube comments as opposed to through this site.

Here's this tutorial in video format:

Create Our Data Source and Populate our ListView

Our data sources, we agreed, will be just arraylist of strings. However we want a multi-column ListView so what do we do? Well for simplicity we will have two arraylists to cater for two columns.

Then for the third column we will use the System. Random to generate random integers to populate our third ListView column.

        private static void populateData()
        {
            ArrayList nebulae = new ArrayList
            {
                "Horse Head", "Black Widow", "Ghost Head", "Cat's Eye", "Elephant's Trunk", "Helix", "Rosette","Snake","Bernad 68",
                "Ant", "Orion", "Butterfly", "Eagle", "Own", "Ring", "Pelican", "Cone", "Flame", "Witch Head", "Bumerang"
            };
            ArrayList nebularCategory = new ArrayList
            {
                "HII REGION ", "REFLECTION NEBULAR", "PLANETARY NEBULAR", "SUPERNOVA REMNANTS",
                "DARK NEBULAR"
            };
            Random r = new Random();
            foreach (string nebular in nebulae)
            {
                myListView.Items.Add(new ListViewItem(new[] { nebular, nebularCategory[r.Next(0, 5)] as string, (r.Next(9, 9999)).ToString() }));
            }
        }

Then we loop through our data adding items to our ListView using the Add() method.

Our main method

Normally it is the main method that is always the entry point to C# executable applications.

        public static void Main()
        {
            setupListView();
            populateData();
            createForm();
        }

In our case our main method has three custom methods:

  • setUpListView() - To instantiate our ListView and add its columns.
  • populateData() - To populate our ListView with data.
  • createForm() - To create our Windows Form and run it.

Full Code

using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ListViewArrayList
{
    static class Program
    {
        private static ListView myListView;
        public static void Main()
        {
            setupListView();
            populateData();
            createMetroForm();
        }

        private static void createForm()
        {
            Form myForm = new Form
            {
                Text = "WinForms ListView ArrayList Example - Camposha.info",
                ClientSize = new Size(564, 520),
                BackColor = Color.Tomato
            };

            myForm.Controls.Add(myListView);
            Application.EnableVisualStyles();
            Application.Run(myForm);
        }
        private static void setupListView()
        {
            myListView = new ListView { Location = new Point(30, 70), Size = new Size(400, 400), View = View.Details, FullRowSelect = true, Alignment = ListViewAlignment.SnapToGrid };
            myListView.Columns.Add("NAME", 100);
            myListView.Columns.Add("CATEGORY", 150);
            myListView.Columns.Add("DISTANCE(Light Years)", 150);

            myListView.ItemSelectionChanged += myListView_ItemSelectionChanged;
        }

        static void myListView_ItemSelectionChanged(object sender, ListViewItemSelectionChangedEventArgs e)
        {
            if (e.IsSelected)
            {
                ListViewItem listViewItem = e.Item;
                MessageBox.Show(listViewItem.SubItems[0].Text);
            }
        }

        private static void populateData()
        {
            ArrayList nebulae = new ArrayList
            {
                "Horse Head", "Black Widow", "Ghost Head", "Cat's Eye", "Elephant's Trunk", "Helix", "Rosette","Snake","Bernad 68",
                "Ant", "Orion", "Butterfly", "Eagle", "Own", "Ring", "Pelican", "Cone", "Flame", "Witch Head", "Bumerang"
            };
            ArrayList nebularCategory = new ArrayList
            {
                "HII REGION ", "REFLECTION NEBULAR", "PLANETARY NEBULAR", "SUPERNOVA REMNANTS",
                "DARK NEBULAR"
            };
            Random r = new Random();
            foreach (string nebular in nebulae)
            {
                myListView.Items.Add(new ListViewItem(new[] { nebular, nebularCategory[r.Next(0, 5)] as string, (r.Next(9, 9999)).ToString() }));
            }
        }
    }
}

Result

C# ListView ArrayList
C# ListView ArrayList

Best Regards,Oclemy.

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *