C# ListBox - Introduction


A ListBox is a windows form component that provides users with a selectable list of items.

With a ListBox users can select one or more items.

In a ListBox, if the total number of items to be rendered exceeds the number that can be displayed in the viewport, then automatically a scrollbar is added.

Alot of people don't know that ListBoxes can also displayed data in multiple columns like ListViews and DataGridView. To do that the MultiColumn has to be set to true.

By default it's always set to false hence displaying data in a single column.

If you prefer that the scrollbar should always appear, then you set the ScrollAlwaysVisible to true.

You can determine how many rows of ListBox items that can be selected at any time using the SelectionMode property.

If you want to get the selected row in the ListBox, you can use the SelectedIndex property which gives you an integer value representing the first selected row.

If no item i selected, then the SelectedIndex defaults to -1.

However, if you just want the selected object but not it's index, then you can use the SelectedItem property.

You can get the total number of items renderd in your ListBox via the Count property.

You can perform CRUD operations in the ListBox with provided methods. To add an item to ListBox you can use the Add(), to insert an item you can use the Insert(), to remove you use Remove() while to clear all items in the ListBox you use the Clear() method.

ListBox API Definition

ListBox is a public class defined in the in the System.Windows.Forms namespace.

namespace System.Windows.Forms;

That namespace itself belongs to System.Windows.Forms.dll assembly.

As a class ListBox derives form System.Windows.Forms.ListControl

public class ListBox : System.Windows.Forms.ListControl

ListControl is an abstract class that provides common implementation of members for the ListBox and the ComboBox classes.

When you work with a ListBox, the Windows System will automatically draw the ListBox items for you.

However, you can override this behavior using the DrawMode property of the ListBox, then handle the MeasureItem and DrawItem events.

If you have massive amounts of items that need to added to your ListBox, performance may be impacted given that each item addition leads to the control being repainted.

However, you can solve that by using the BeginUpdate and EndUpdate methods. These allow you to add those data without the control being repainted every time an item is added. This makes it efficient.

You can also search a ListBox using the FindString and FindStringExact() methods.

You can also bind items to a ListBox using the DataSource property.

Example

Let's look at an example to populate a ListBox from an Array of data.

using System;
using System.Drawing;
using System.Windows.Forms;

namespace Mr_ListBox
{
    static class Program
    {
        private static readonly ListBox myListBox = new ListBox
        {
            Location = new Point(30, 70),
            Size = new Size(500, 400),
            Font = new Font(FontFamily.GenericSansSerif, 15)
        };
        /*
        * Generate data and populate our ListBox
        */
        private static void populateListBox()
        {
            String[] nebulae =
                {
                    "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"
                };
            foreach (string nebular in nebulae)
            {
                myListBox.Items.Add(nebular);
            }

            myListBox.SelectedIndexChanged += myListBox_SelectedIndexChanged;
        }
        /*
         * ListBox SelectedIndexChanged event handler. We display a messagebox when item is selected.
         */
        private static void myListBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                int selectedIndex = myListBox.SelectedIndices[0];
                if (selectedIndex != -1)
                {
                    string name = myListBox.Items[selectedIndex].ToString();
                    MessageBox.Show(name);
                }
            }
            catch (ArgumentOutOfRangeException argumentOutOfRangeException)
            {
                MessageBox.Show(argumentOutOfRangeException.Message);
            }
        }
        /*
     * Create a Form, Set its properties and run the application.
     */
        private static void createForm()
        {
            Form myForm = new Form
            {
                Text = "C# WinForms : ListBox - Fill From Array - Camposha.info",
                ClientSize = new Size(564, 520),
                BackColor = Color.MediumSeaGreen
            };

            myForm.Controls.Add(myListBox);
            populateListBox();
            Application.EnableVisualStyles();
            Application.Run(myForm);
        }
        /*
        * Main method
        */
        public static void Main()
        {
            createForm();
        }

    }
}

And that's it.

How do You Feel after reading this?

According to scientists, we humans have 8 primary innate emotions: joy, acceptance, fear, surprise, sadness, disgust, anger, and anticipation. Feel free to tell us how you feel about this article using these emotes or via the comment section. This feedback helps us gauge our progress.

Help me Grow.

I set myself some growth ambitions I desire to achieve by this year's end regarding this website and my youtube channel. Am halfway. Help me reach them by:




Recommendations


What do You Think

Dear readers drop us your comments below. We are building a community of students and learners. Start by dropping us your suggestions below. What tutorials do you want us to do for example? Where can we improve? What are some awesome resources out there? Do you have any code you want to share with us?
By the way that example or snippet you have lying in your computer can really help beginner programmers. We can share it here with other students.

Previous Post Next Post