Question First time I've used a ListBox

357mag

Well-known member
Joined
Mar 31, 2023
Messages
58
Programming Experience
3-5
I thought I could look in the ListBox properties and see the item index number for each item I put in my ListBox, but I saw nothing like that. Then I guess we let C# handle those details.
 
This is not a C# general question. The ListBox is a control so the question relates specifically to the GUI technology you're using and may be different for different technologies. This thread has been moved to the Windows Forms forum. If you are using a different technology, please specify and we can move it again. Please post in the most specific forum applicable to the issue. General forums should be the last resort.
 
As is the case for most WinForms controls, and many other classes throughout the framework, the ListBox has a property that refers to a collection of the items it contains. As is quite common, that property is named Items. Sometimes the items in such a collection will be a dedicated type but, in the case of the ListBox control, they are all just object references, as the control can contain items of any type and even mixed types. As with most other collections, you can index it to get an item at a specific index or you can enumerate it to access each item in turn:
C#:
// Access each item by index.
for (var i = 0; i < myListBox.Items.Count; i++)
{
    var item = (SomeType)myListBox.Items[i];
    
    // Use item here.
}

// Enumerate the items.
foreach (SomeType item in myListBox.Items)
{
    // Use item here.
}
Because each item is an object reference, you need to cast it as its actual type to use it as that type. For instance, if you bind a DataTable to a ListBox, each item will be type DataRowView.
 
Back
Top Bottom