The ListBox class gives programmers a way to display a list of elements in a separate window.
There are two ways to implement a ListBox.
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.
Another way is to programmatically create and edit a ListBox using C# code:
// Declaring objectListBox listBoxSample = new ListBox();// Initializing ListBox Properties// Setting LocationlistBoxSample.Location = new System.Drawing.Point(0, 0);// Setting NamelistBoxSample.Name = "ListBoxShotSample";// Setting SizelistBoxSample.Size = new System.Drawing.Size(150, 100);// Setting Background ColorlistBoxSample.BackColor = System.Drawing.Color.White;// Setting Foreground ColorlistBoxSample.ForeColor = System.Drawing.Color.Black;// Setting FontlistBoxSample.Font = new Font("Times New Roman", 12);// Setting Border StylelistBoxSample.BorderStyle = BorderStyle.FixedSingle;// Adding ElementslistBoxSample.Items.Add("Font");listBoxSample.Items.Add("Size");listBoxSample.Items.Add("Location");listBoxSample.Items.Add("Background Color");listBoxSample.Items.Add("ForeColor");// Spawning ListBox once readyControls.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