Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I add an item to a ListBox in C# and WinForms?

Tags:

c#

winforms

I'm having trouble figuring out how to add items to a ListBox in WinForms.

I have tried:

list.DisplayMember = "clan";
list.ValueMember = sifOsoba;

How can I add ValueMember to the list with an int value and some text for the DisplayMember?

list.Items.add(?)

Btw. I can't use ListBoxItem for any reasons.

like image 568
Ante Avatar asked Nov 13 '09 21:11

Ante


People also ask

How do I add items to my ListBox?

To add items to a ListBox, select the ListBox control and get to the properties window, for the properties of this control. Click the ellipses (...) button next to the Items property. This opens the String Collection Editor dialog box, where you can enter the values one at a line.

How do I add and remove items from ListBox?

When a user enters some text into a TextBox and clicks on the add Button, text will be shown in the ListBox. After that, select text from the ListBox and click on the Delete Button to remove the text from the ListBox control.

How do I bind ListBox?

To bind a ComboBox or ListBox control If you are binding to a table, set the DisplayMember property to the name of a column in the data source. If you are binding to an IList, set the display member to a public property of the type in the list.

How does ListBox work in 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.


3 Answers

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)

like image 76
AZ. Avatar answered Oct 21 '22 18:10

AZ.


list.Items.add(new ListBoxItem("name", "value"));

The internal (default) data structure of the ListBox is the ListBoxItem.

like image 23
monksy Avatar answered Oct 21 '22 20:10

monksy


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.

like image 9
John Rudy Avatar answered Oct 21 '22 18:10

John Rudy