C# ListBox Control
The ListBox control enables you to display a list of items to the user that the user can select by clicking.
Setting ListBox Properties
You can set ListBox properties by using Properties Window. In order to get Properties window you can Press F4 or by right-clicking on a control to get the «Properties» menu item.

You can set property values in the right side column of the property window.
C# Listbox example
Add Items in a Listbox
Syntax
In addition to display and selection functionality, the ListBox also provides features that enable you to efficiently add items to the ListBox and to find text within the items of the list. You can use the Add or Insert method to add items to a list box. The Add method adds new items at the end of an unsorted list box.
If the Sorted property of the C# ListBox is set to true, the item is inserted into the list alphabetically. Otherwise, the item is inserted at the end of the ListBox.
Insert Items in a Listbox
Syntax
You can inserts an item into the list box at the specified index.
Listbox Selected Item
If you want to retrieve a single selected item to a variable , use the following code.
Selecting Multiple Items from Listbox
The SelectionMode property determines how many items in the list can be selected at a time. A ListBox control can provide single or multiple selections using the SelectionMode property . If you change the selection mode property to multiple select , then you will retrieve a collection of items from ListBox1.SelectedItems property.
The ListBox class has two SelectionMode. Multiple or Extended .
In Multiple mode , you can select or deselect any item in a ListBox by clicking it. In Extended mode, you need to hold down the Ctrl key to select additional items or the Shift key to select a range of items.
The following C# program initially fill seven days in a week while in the form load event and set the selection mode property to MultiSimple . At the Button click event it will display the selected items.
Getting All Items from List box
The Items collection of C# Winforms Listbox returns a Collection type of Object so you can use ToString() on each item to display its text value as below:
How to bind a ListBox to a List ?
You can bind a List to a ListBox control by create a fresh List Object and add items to the List.
Creating a List
Binding to List
The next step is to bind this List to the Listbox. In order to do that you should set datasource of the Listbox.
How to bind a listbox to database values ?
First of all, you could create a connection string and fetch data from database to a Dataset.
Set Datasource for ListBox
Next step is that you have set Listbox datasoure as Dataset.
How to refresh DataSource of a ListBox ?
When you want to clear the Listbox, if the ListBox already binded with Datasource , you have to set the Datasource of Listbox as null.
How to SelectedIndexChanged event in ListBox ?
This event is fired when the item selection is changed in a ListBox . You can use this event in a situation that you want select an item from your listbox and accodring to this selection you can perform other programming needs.
You can add the event handler using the Properties Window and selecting the Event icon and double-clicking on SelectedIndexChanged as you can see in following image.
The event will fire again when you select a new item. You can write your code within SelectedIndexChanged event . When you double click on ListBox the code will automatically come in you code editor like the following image.
From the following example you can understand how to fire the SelectedIndexChanged event.
First you should drag two listboxes on your Form. First listbox you should set the List as Datasource , the List contents follows:
When you load this form you can see the listbox is populated with List and displayed first quarter and second quarter. When you click the «Fist Quarter» the next listbox is populated with first quarter months and when you click «Second Quarter» you can see the second listbox is changed to second quarter months. From the following program you can understand how this happened.
C# Listbox Column
A multicolumn ListBox places items into as many columns as are needed to make vertical scrolling unnecessary. The user can use the keyboard to navigate to columns that are not currently visible. First of all, you have Gets or sets a value indicating whether the ListBox supports multiple columns .
The following C# code example demonstrates a simple muliple column ListBox.
Listbox Item Double Click Event
Add an event handler for the Control.DoubleClick event for your ListBox.
The following program shows when you double click the Listbox Item that event handler open up a MessageBox displaying the selected item.
Listbox vertical scrollbar
ListBox only shows a vertical scroll bar when there are more items then the displaying area. You can fix with ListBox.ScrollAlwaysVisible Property if you want the bar to be visible all the time. If ListBox.ScrollAlwaysVisible Property is true if the vertical scroll bar should always be displayed; otherwise, false. The default is false.
Background and Foreground
The Listbox BackColor and ForeColor properties are used to set the background and foreground colors respectively. If you click on these properties in the Properties window, then the Color Dialog pops up and you can select the color you want.
Alternatively, you can set background and foreground colors from source code. The following code sets the BackColor and ForeColor properties:
How to clear all data in a listBox?
Listbox Items.Clear() method clear all the items from ListBox.
ListBox.ClearSelected Method Unselects all items in the ListBox.
Remove item from Listbox
RemoveAt method removes the item at the specified index within the collection. When you remove an item from the list, the indexes change for subsequent items in the list. All information about the removed item is deleted.
Listbox Vs ListView Vs GridView
C# ListBox has many similarities with ListView or GridView (they share the parent class ItemsControl), but each control is oriented towards different situations. ListBox is best for general UI composition, particularly when the elements are always intended to be selectable, whereas ListView or GridView are best for data binding scenarios, particularly if virtualization or large data sets are involved. One most important difference is listview uses the extended selection mode by default .
Как заполнить listbox c
In Windows Forms, ListBox control is used to show multiple elements in a list, from which a user can select one or more elements and the elements are generally displayed in multiple columns. The ListBox class is used to represent the windows list box and also provide different types of properties, methods, and events. It is defined under System.Windows.Forms namespace. The ListBox class contains three different types of collection classes, i.e.
- ListBox.ObjectCollection: This class holds all the elements contained in the ListBox control.
- ListBox.SelectedObjectCollection: This class holds a collection of the selected items which is a subset of the items contained in the ListBox control.
- ListBox.SelectedIndexCollection: This class holds a collection of the selected indexes, which is a subset of the indexes of the ListBox.ObjectCollection and these indexes specify elements that are selected.
In C# you can create a ListBox in the windows form by using two different ways:
1. Design-Time: It is the easiest way to create a ListBox as shown in the following steps:
- Step 1: Create a windows form as shown in the below image:
Visual Studio -> File -> New -> Project -> WindowsFormApp
- Step 2: Next, drag and drop the ListBox control from the toolbox to the form.
2. Run-Time: It is a little bit trickier than the above method. In this method, you can create a ListBox control programmatically with the help of syntax provided by the ListBox class. The following steps show how to set the create ListBox dynamically:
- Step 1: Create a ListBox control using the ListBox() constructor is provided by the ListBox class.
- Step 2: After creating ListBox control, set the property of the ListBox control provided by the ListBox class.
- Step 3: And last add this ListBox control to the form using the following statement:
Как заполнить listbox c
Элемент ListBox представляет собой простой список. Ключевым свойством этого элемента является свойство Items , которое как раз и хранит набор всех элементов списка.
Элементы в список могут добавляться как во время разработки, так и программным способом. В Visual Studio в окне Properties (Свойства) для элемента ListBox мы можем найти свойство Items. После двойного щелчка на свойство нам отобразится окно для добавления элементов в список:

В пустое поле мы вводим по одному элементу списка — по одному на каждой строке. После этого все добавленные нами элементы окажутся в списке, и мы сможем ими управлять:

Программное управление элементами в ListBox
Добавление элементов
Итак, все элементы списка входят в свойство Items , которое представляет собой коллекцию. Для добавления нового элемента в эту коллекцию, а значит и в список, надо использовать метод Add, например: listBox1.Items.Add(«Новый элемент»); . При использовании этого метода каждый добавляемый элемент добавляется в конец списка.
Можно добавить сразу несколько элементов, например, массив. Для этого используется метод AddRange :
Вставка элементов
В отличие от простого добавления вставка производится по определенному индексу списка с помощью метода Insert :
В данном случае вставляем элемент на вторую позицию в списке, так как отсчет позиций начинается с нуля.
Удаление элементов
Для удаления элемента по его тексту используется метод Remove :
Чтобы удалить элемент по его индексу в списке, используется метод RemoveAt :
Кроме того, можно очистить сразу весь список, применив метод Clear :
Доступ к элементам списка
Используя индекс элемента, можно сам элемент в списке. Например, получим первый элемент списка:
Свойство Count возвращает количество элементов в списке:
Выделение элементов списка
При выделении элементов списка мы можем ими управлять как через индекс, так и через сам выделенный элемент. Получить выделенные элементы можно с помощью следующих свойств элемента ListBox:
SelectedIndex : возвращает или устанавливает номер выделенного элемента списка. Если выделенные элементы отсутствуют, тогда свойство имеет значение -1
SelectedIndices : возвращает или устанавливает коллекцию выделенных элементов в виде набора их индексов
SelectedItem: возвращает или устанавливает текст выделенного элемента
SelectedItems : возвращает или устанавливает выделенные элементы в виде коллекции
По умолчанию список поддерживает выделение одного элемента. Чтобы добавить возможность выделения нескольких элементов, надо установить у его свойства SelectionMode значение MultiSimple .
Чтобы выделить элемент програмно, надо применить метод SetSelected(int index, bool value) , где index — номер выделенного элемента. Если второй параметр — value имеет значение true , то элемент по указанному индексу выделяется, если false , то выделение наоборот скрывается:
Чтобы снять выделение со всех выделенных элементов, используется метод ClearSelected .
Событие SelectedIndexChanged
Из всех событий элемента ListBox надо отметить в первую очередь событие SelectedIndexChanged , которое возникает при изменении выделенного элемента:
В данном случае по выбору элемента списка будет отображаться сообщение с выделенным элементом.
How can I add an item to a ListBox in C# and WinForms?
I’m having trouble figuring out how to add items to a ListBox in WinForms.
How can I add ValueMember to the list with an int value and some text for the DisplayMember ?
Btw. I can’t use ListBoxItem for any reasons.
![]()
9 Answers 9
ListBoxItem is a WPF class, NOT a WinForms class.
For WPF, use ListBoxItem.
For WinForms, the item is a Object type, so use one of these:
1. Provide your own ToString() method for the Object type.
2. Use databinding with DisplayMemeber and ValueMember (see Kelsey’s answer)
The internal (default) data structure of the ListBox is the ListBoxItem.
In WinForms, ValueMember and DisplayMember are used when data-binding the list. If you’re not data-binding, then you can add any arbitrary object as a ListItem .
The catch to that is that, in order to display the item, ToString() will be called on it. Thus, it is highly recommended that you only add objects to the ListBox where calling ToString() will result in meaningful output.