JavaScript Error

You currently have JavaScript disabled on your web browser.

This website uses JavaScript, and This web page needs JavaScript activated to work correctly.

Please active JavaScript on your web browser and then refresh this web page.



ListBox



example1

The ListBox control is found in the System.Windows.Forms namespace within the System.Windows.Forms.dll. In this blog post I am referring to the ListBox control that is available in C# .NET-Core (.NET 6.0) with Visual Studio 2022 (although this code example might still work OK with older .NET versions).

The purpose and function of a ListBox control is to display a list of items to the user. The user can select one or multiple items listed in the ListBox control by clicking on them (multiple item selection is available by setting the SelectionMode property). Unlike a ComboBox, which displays the list of items in a drop down list region, the ListBox control displays the items in a boxed region.

The ListBox can also display items in columns instead of in a straight vertical list, by setting the MultiColumn property.

The default DrawMode property is to allow Windows to handle the task of drawing the items displayed, however you can set the DrawMode to owner drawn mode, and handle the MeasureItem and DrawItem events so that you can override the automatic drawing and draw the items yourself. With owner-drawn mode you can display variable-height items, images, or a different color or font for the text of each item in the list. The HorizontalExtent property, GetItemHeight, and GetItemRectangle also help you to customize drawing your own items.

The BeginUpdate and EndUpdate methods enable you to add a large number of items to the ListBox control object without the control being repainted each time an item is added to the list.

The ListBox control object has three collections, accessible by the Items, SelectedItems, and SelectedIndices properties. The Items collection contains all items contained in the ListBox control. The SelectedItems contains a collection of the selected items which is a subset of the items contained in the ListBox control. The SelectedIndices contains a collection of selected indexes, which is a subset of the indexes of the Items collection, which specify the items that are selected by their index values.


Example Source Code

This example uses a ListBox control, along with a Label control.

To add the ListBox control to your form, you can double click on its name (i.e. ListBox) as listed in the Toolbox window panel within the Form editor window. Alternatively, you can single click on it and then drag and drop it onto your form, to position it more closer to where you want it to be positioned at. Once it is added to the form then it will appear on the forms surface area having default control values.

After you have added the ListBox control to your form, then once you select it then you can view and edit that objects property values in the Properties window within the Forms editor window, where you can then change the controls Name, Items, and other properties as you desire.

In the following example, I added a ListBox control to the Form, as well as a Label control. I did not alter any of the ListBox control objects properties and just use its default property values as is. After selecting the Label control, I set its AutoSize property to False and then resized the control to fit the form, as well as changed its BorderStyle property to Fixed3D:

example2

From the Form editor, I double clicked on the ListBox control object that I had just added to the Form. Doing so automatically created and linked a callback method to that controls SelectedIndexChanged event into that forms .cs source code file, which I then programed some action to be performed whenever the user clicks or selects an item from the ListBox control object. I also added code to the forms Load event method to initialize the ListBox control object with a list of Items, and set the label's Text property with a default string value:

 
namespace TestProgram
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            // add items to the ListBox
            listBox1.Items.AddRange(new object[] {
            "Cat",
            "Dog",
            "Bird",
            "Fish"});
            
            // set default label text
            label1.Text = "Select an item above...";
        }

        private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            // get the current item
            string? tempText = listBox1.SelectedItem.ToString();

            // check which item it is and display feedback
            if (tempText != null)
            {
                if (tempText == "Cat")
                {
                    label1.Text = "Cats are small carnivorous mammals. The scientific name for Cat is Felis catus.";
                }
                else if (tempText == "Dog")
                {
                    label1.Text = "Dogs are descendants of the wolf.";
                }
                else if (tempText == "Bird")
                {
                    label1.Text = "There are over 10,000 different species of birds around the world.";
                }
                else if (tempText == "Fish")
                {
                    label1.Text = "The whale shark is the largest fish, measuring over 18 meters in length.";
                }
                else
                {
                    label1.Text = "Select an item above...";
                }
            }
        }
		
    }
}

When you run the above examples and click on an item from the ListBox control object then you should see something similar to the following:

example3 example4 example5

Final Thoughts

Thank you for reading, I hope you found this blog post (tutorial) educational and helpful.


(0) pollYesResult
(0) pollNoResult



 
     About   |   Contact Us   |   Privacy   |   Terms & Conditions   |   © 2024 - T&J Divisions, LLC, All Rights Reserved