- This topic explains about how to add items to listbox and remove items from listbox in C# programming.
- Tools needed: ListBox (ListBox1), Button1(btnAdd), Button2(btnClear)
ListBox Class – Add items to listbox and remove items from listbox in C#
- ListBox contains a list of selected items.
Namespace: System.Windows.Controls
Assembly: PresentationFramework (in PresentationFramework.dll)
- Syntax for ListBox
|
1 2 3 |
[LocalizabilityAttribute(LocalizationCategory.ListBox)] [StyleTypedPropertyAttribute(Property = "ItemContainerStyle", StyleTargetType = typeof(ListBoxItem))] public class ListBox : Selector |
ListBox.Items property – Add items to listbox and remove items from listbox in C#
- Get the items of the ListBox
- Syntax
|
1 2 3 |
// Declaration public ListBox.ObjectCollection Items { } |
- This property enables you to obtain a reference to the list of items that are currently stored in the ListBox.
- With this reference, you can add items, remove items, and obtain a count of the items in the collection.
- You can also manipulate the items of a ListBox by using the DataSource property
To add items to ListBox – Add items to listbox and remove items from listbox in C#
|
1 |
listBox1.Items.Add("ListData1"); |
To clear items from ListBox – Add items to listbox and remove items from listbox in C#
|
1 |
listBox1.Items.Clear(); |
ListBox.SelectedIndex Property – Add items to listbox and remove items from listbox in C#
- It helps to gets or sets the zero-based index of the currently selected item from the ListBox.
NameSpace: System.Windows.Forms
Assembly: System.Windows.Forms (in System.Windows.Forms.dll)
- Syntax:
|
1 2 3 4 5 |
// Declaration [BindableAttribute(true)] [BrowsableAttribute(false)] public override int SelectedIndex { } |
Add items to listbox and remove items from listbox in C# – Complete Code
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace WindowsFormsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { } private void btnAdd_Click(object sender, EventArgs e) { // To add items to the listbox listBox1.Items.Add("ListData1"); listBox1.Items.Add("ListData2"); listBox1.Items.Add("ListData3"); } private void btnClear_Click(object sender, EventArgs e) { // To clear listbox items' listBox1.Items.Clear(); } } } |
Add items to listbox and remove items from listbox in C#






