简体   繁体   中英

Populate a Listbox from a database

I want to fill my ListBox 'lstCategories' with the content of a database and all I see is nothing, here's the code :

public void FillCategories()
{
    SamsonEntities db = new SamsonEntities();

    var ListCats = (from cat in db.Categories
                    select new CategoryDisplay()
                    {
                        CategoryID = cat.CategoryID,
                        CategoyName = cat.CategoryName
                    }).ToList();

     //for (var i = 0; i < db.Categories.Count();i++ )
     //{
     //    lstCategories.Items.Add(....);
     //}
}

I don't know what to place into the line of my 'for', so I put it in comments

Have you tried setting the list as the ListBox datasource?

 lstCategories.DataSource = ListCats;

That should be enough.

As per your comment you need to set up the DisplayMember of your list to match the property to show:

lstCategories.DisplayMember = "CategoryName";

And you probably want to setup the ValueMember too:

lstCategories.ValueMember = "CategoryID";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM