How to Add an Item to a ListBox in C# and WinForms
The ListBox
control is used in WinForms to display several items in a list, from which a user can pick one or more elements, and the components are often presented in multiple columns. This tutorial will discuss how to add an item to a ListBox
using the C# and WinForms.
Methods to Add an Item to a ListBox
Method 1 - Drag & Drop in WinForms
To add items to the ListBox
in the WinForms, follow the below steps.
-
Create a new
Windows Forms
project inVisual Studio
and give it a meaningful name -
Now, from the left panel of
ToolBox
search forListBox
-
Drag and drop it to the windows form
-
To add new items to the
ListBox
, right-click theListBox
-
In the Properties, find
Items
and click on three dots, then add items and click onOK
-
Lastly, run the windows-form
Output:
Method 2 - Write Code in C# to Manually Add Items in ListBox
You can manually add the items in the ListBox
by writing code. Let’s look at an example to grasp this concept better.
-
To begin, import the following libraries
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms;
-
Create a
ListBox
list namedshaniList
ListBox shaniList = new ListBox();
-
Then, we’ll add the item to the list as shown below
shaniList.Items.Add("Cut"); shaniList.Items.Add("Paste"); shaniList.Items.Add("Copy");
-
Add a
ListBox
control to the form byControls.Add()
as the last stepthis.Controls.Add(shaniList);
Complete Source Code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace AddItemtoListBoxbyZeeshan {
public partial class Form1 : Form {
public Form1() {
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e) {
ListBox shaniList = new ListBox();
shaniList.Location = new Point(150, 70);
shaniList.Items.Add("Cut");
shaniList.Items.Add("Paste");
shaniList.Items.Add("Copy");
this.Controls.Add(shaniList);
}
}
}
Output:
I have been working as a Flutter app developer for a year now. Firebase and SQLite have been crucial in the development of my android apps. I have experience with C#, Windows Form Based C#, C, Java, PHP on WampServer, and HTML/CSS on MYSQL, and I have authored articles on their theory and issue solving. I'm a senior in an undergraduate program for a bachelor's degree in Information Technology.
LinkedIn