Avatar of Scott Baldridge
Scott Baldridge
 asked on

Help with IEnumerable Collection

Hello, I need some help understanding how to accomplish this task:

Given a class called Product with a shared method GetProducts() that returns an IEnumerable collection of Product objects with the properties ID and Desc, how would you populate a drop down list?
Microsoft Development

Avatar of undefined
Last Comment
Scott Baldridge

8/22/2022 - Mon
Jacques Bourgeois (James Burger)

IEnumerable is an Interface, it is not an object. All collections in .NET are IEnumerable. It is only a small subset of the collection that enables you to use it in a loop. You can always loop through the collection through IEnumerable and fill the dropdown item by item, but there is an alternative that is more interesting.

.NET collections also implement IList, which is what you are usually after when you want to fill a list of a grid with data.

Find what you have hidden under your IEnumerable collection, and use that type instead of IEnumerable. You can see what is hiding there by hitting a breakpoint when there is something in the collection. Examine the collection in the debugger, and you will have its type somewhere in there.

Using the collection by its real type instead of through one of its interfaces, you simply fill your dropdown the following way, assuming that yu are in a Windows Application. There is something similar but maybe somewhat different for Web applications.

yourDropDown.DataSource = yourCollectionObject; // This fills your dropdown with the collection
yourDropDown.DisplayMember = "Desc";

Once the user has made a selection, you can use yourDropDown.Text to retrieve the selected description, and yourDropDown.SelectedValue to get the ID.
Scott Baldridge

Thank you for the explanation! So much to learn and I'm new to C#.

Would something like this work?

myProducts IList = Products.GetPlatforms();
ddlProducts.TextField = "Desc;
ddlProducts.ValueField = "ID";
ddlProducts.DataSource = myProducts;
Jacques Bourgeois (James Burger)

Log in or sign up to see answer
Become an EE member today7-DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform
Sign up - Free for 7 days
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.
Not exactly the question you had in mind?
Sign up for an EE membership and get your own personalized solution. With an EE membership, you can ask unlimited troubleshooting, research, or opinion questions.
ask a question
Scott Baldridge

Thank you for your time and help explaining. I really appreciate your help! I need to read some more.
Experts Exchange has (a) saved my job multiple times, (b) saved me hours, days, and even weeks of work, and often (c) makes me look like a superhero! This place is MAGIC!
Walt Forbes