Link to home
Start Free TrialLog in
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?
Avatar of Jacques Bourgeois (James Burger)
Jacques Bourgeois (James Burger)
Flag of Canada image

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";
yourDropDown.DisplayValue="ID";

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

ASKER

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;
ddlProducts.DataBind();
ASKER CERTIFIED SOLUTION
Avatar of Jacques Bourgeois (James Burger)
Jacques Bourgeois (James Burger)
Flag of Canada image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Thank you for your time and help explaining. I really appreciate your help! I need to read some more.