How to bundle gridview using linq / Entity Framework?

I need to bind a GridView , I use this code:

  ProductDBEntities db = new ProductPDBEntities(); var pro = from u in db.Products where u.PID == 1 select u; if (pro != null) { GridView1.DataSource = pro; GridView1.DataBind(); } 

and get this error.

System.InvalidOperationException: Sequence contains more than one Element

Can someone please tell me what I am doing wrong?

+6
source share
5 answers

Check Duplication , and then try linking it.

I edited my last answer to display the full code:

 ProductDBEntities db = new ProductPDBEntities(); GridView1.DataSource = (from u in db.Products where u.PID == 1 select u).First(); GridView1.DataBind(); 
+2
source

This code might be useful:

  gv.DataSource = (from u in db.Products .First(u=> u.PID==1)).ToList(); 

If you have a table and a table in detail can use this:

  gv.DataSource = (from a in context.tblorder.First(p => p.id == 19).tblorderdetail where a.ID == 19 select a).ToList(); 
+1
source

You can check your details first to see if there is more than one product with PID = 1.

Secondly, you can use the .First () method to make sure that you get only one result for binding:

 var pro = (from u in db.Products where u.PID == 1 select u).First(); 
0
source

I think you need to do ToList() when added to a DataSource :

 ProductDBEntities db = new ProductPDBEntities(); var pro = from u in db.Products where u.PID == 1 select u; if (pro != null) { GridView1.DataSource = pro.ToList(); GridView1.DataBind(); } 

Note. Since this is a GridView , you need to take n number of rows. No row limit .

0
source

Save the object type variable and assign the object type as the data source for the grid

0
source

Source: https://habr.com/ru/post/887185/


All Articles