Click here to Skip to main content
15,946,179 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
SQL
I have a problem with binding Listview to my database using entity framwork.
This code only shows the first row of the table but the records do not show:


C#
var item = (from p in db.tbl_film
            select p).FirstOrDefault();
string[] items = {item.flm_id.ToString(),item.flm_name,item.flm_description,item.flm_category };
foreach (var itemlist in items)
{
    ListViewItem lvi = new ListViewItem(items);
    listView1.Items.Add(lvi);
}
Posted

Your query returns the first record always because you have used
FirstOrDefault();
in your linq query
 
Share this answer
 
instead of FirstOrDefault() use ToList() in your query.You will get all the records from database.FirstOrDefault() instructs Entity framework to return first record of table only.

C#
var items = (from p in db.tbl_film
            select p).ToList();
foreach (var itemlist in items)
{
    ListViewItem lvi = new ListViewItem();
    lvi.Id=itemlist.Id;
    lvi.Name= itemlist.Name;
    //And so on...
    listView1.Items.Add(lvi);
}
 
Share this answer
 
Comments
Member 10010636 21-Aug-13 8:39am    
ID and Name
Where do they come from?
Jitendra Sabat 21-Aug-13 8:45am    
I just assume that your ListViewItem class has Id and Name property,to which i have assigned dynamically fetched data from Linq query.I also assume that my record from table will have Id and Name property as its members.
Member 10010636 21-Aug-13 9:11am    
Is this correct code of rules and standards??
Jitendra Sabat 21-Aug-13 9:13am    
Yes of course.You can implement if you want.
Only error when writing ListviewItem meets with a sample please let me thank you

C#
var items = (from p in db.tbl_film select p).ToList();
         foreach (var item in items)
         {
             ListViewItem lvi = new ListViewItem(??????);
         }
 
Share this answer
 
C#
var items = (from p in db.tbl_film
                         select new {
                             ID=p.flm_id,name=p.flm_name,description=p.flm_description,link=p.flm_link,sub=p.flm_sub_link,cate=p.flm_category,pic=p.flm_pic
                         });
            foreach (var itemlist in items)
            {
                ListViewItem lvi = new ListViewItem(itemlist.ID.ToString());
                lvi.SubItems.Add(itemlist.name);
                lvi.SubItems.Add(itemlist.description);
                lvi.SubItems.Add(itemlist.link);
                lvi.SubItems.Add(itemlist.sub);
                lvi.SubItems.Add(itemlist.cate);
                lvi.SubItems.Add(itemlist.pic);
                listView1.Items.Add(lvi);
            }
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900