开发者

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 i开发者_运维百科n 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.

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:

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;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜