简体   繁体   English

使用来自动态数据库C#的成员填充ComboBox项

[英]Populating ComboBox Items with members from a dynamic database, C#

My database, db, has as a primary key 'Artist' with foreign key 'CdTitle', in one form a user can enter information to add to the database, in another form, I have a combobox that I want to populate with the names of the artist in the database, primarily 'Artist.Names' I've tried using a LINQ to traverse the database and put the results of the query into the combobox but it's not working like i thought. 我的数据库db具有主键“ Artist”和外键“ CdTitle”,在一种形式中,用户可以输入要添加到数据库中的信息,在另一种形式中,我有一个组合框,我想用名称填充数据库中艺术家的名字,主要是“ Artist.Names”,我尝试使用LINQ遍历数据库并将查询结果放入组合框,但它的工作方式与我想象的不同。

the code I have is : 我的代码是:

var ArtistNames = 
    from name in formByArtist.db.Artists    
    select name.Name;

foreach (var element in ArtistNames)
{
    comboBox1.Items.Add(element.ToString());                               
}

Suposing your Artist have a Name and an Id, you can do this: 假设您的艺术家有一个名字和一个ID,您可以这样做:

comboBox1.DataValueField = "Id";
comboBox1.DataTextField = "Name";

comboBox1.DataSource = formByArtist.db.Artists;
comboBox1.DataBind();

From your existing sample, modify as follows: 在您现有的示例中,进行如下修改:

var ArtistNames = 
    (from name in formByArtist.db.Artists    
     select name.Name)
    .ToList();

comboBox1.DataSource = ArtistNames;

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

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