haydnD
haydnD

Reputation: 2293

why do I only get nulls in this IEnumerable<>

I'm trying to populate this IEnumerable with values from a db.

I can't see what I'm doing wrong.

IEnumerable<Categories> categories = new List<Categories>();

List<SelectListItem> catItems = new List<SelectListItem>();

foreach (var cats in categories)
{
    catItems.Add(new SelectListItem
                     {
                         Text = cats.CategoryName,
                         Value = cats.CategoryID.ToString()
                     });
}

Here is the class:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;

namespace SportsStore.Domain.Entities
{
    public class Categories
    {
        [Key]
        public int CategoryID { get; set; }
        public string CategoryName { get; set; }
    }

}

Upvotes: 0

Views: 87

Answers (3)

Forty-Two
Forty-Two

Reputation: 7605

Because here you create a new (and empty) list of Categories:

IEnumerable<Categories> categories = new List<Categories>();

and here you try to iterate over the empty list:

foreach (var cats in categories)
{

Which means you're never adding anything to cat.Items

Upvotes: 0

podiluska
podiluska

Reputation: 51494

How are you populating the categories list? It won't just get filled by saying...

IEnumerable<Categories> categories = new List<Categories>(); 

You need populate it somehow.

Upvotes: 2

Justin Niessner
Justin Niessner

Reputation: 245419

You only ever initialize a new collection of categories, there are never any added to the collection.

Upvotes: 7

Related Questions