How to use ListBox in C#

ListBox

The ListBox class gives programmers a way to display a list of elements in a separate window.

svg viewer

Usage

There are two ways to implement a ListBox.

Using Visual Studio GUI Designer

A ListBox can be easily designed using Visual Studio’s tools. Inside a project, the programmer can spawn a ListBox from the toolbox. Once created, the ListBox can be populated with elements, resized, relocated, and have its properties edited.

Using Code

Another way is to programmatically create and edit a ListBox using C# code:

// Declaring object
ListBox listBoxSample = new ListBox();
// Initializing ListBox Properties
// Setting Location
listBoxSample.Location = new System.Drawing.Point(0, 0);
// Setting Name
listBoxSample.Name = "ListBoxShotSample";
// Setting Size
listBoxSample.Size = new System.Drawing.Size(150, 100);
// Setting Background Color
listBoxSample.BackColor = System.Drawing.Color.White;
// Setting Foreground Color
listBoxSample.ForeColor = System.Drawing.Color.Black;
// Setting Font
listBoxSample.Font = new Font("Times New Roman", 12);
// Setting Border Style
listBoxSample.BorderStyle = BorderStyle.FixedSingle;
// Adding Elements
listBoxSample.Items.Add("Font");
listBoxSample.Items.Add("Size");
listBoxSample.Items.Add("Location");
listBoxSample.Items.Add("Background Color");
listBoxSample.Items.Add("ForeColor");
// Spawning ListBox once ready
Controls.Add(listBoxSample);

This example code shows how a ListBox object is declared, its properties initialized, and its elements added. The location property is defined by a Point object that takes a (x, y) coordinate pair, in the order it is ordered, in its constructor. The Size object similarly takes a (width, height) pair in its constructor. The other properties are quite self-explanatory. When the ListBox is ready for deployment, Controls.Add() function spawns it.

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved