简体   繁体   English

从数据库填充列表框

[英]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 : 我想用数据库的内容填充ListBox'lstCategories',我所看到的只是一无是处,这是代码:

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 我不知道在“ for”行中放置什么内容,因此在注释中添加了它

Have you tried setting the list as the ListBox datasource? 您是否尝试过将列表设置为ListBox数据源?

 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: 根据您的评论,您需要设置列表的DisplayMember以匹配要显示的属性:

lstCategories.DisplayMember = "CategoryName";

And you probably want to setup the ValueMember too: 您可能也想设置ValueMember:

lstCategories.ValueMember = "CategoryID";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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