How to bind gridview using linq/Entity Framework?

心不动则不痛 提交于 2019-12-12 08:44:24

问题


I need to bind GridView, I am using 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 getting this error.

System.InvalidOperationException: Sequence contains more than one element

Can somebody please tell me what am I doin wrong?


回答1:


Check Duplication and then try to bind it.

I have edited my last answer in order to display the complete code :

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



回答2:


This code may be helpful:

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

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

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



回答3:


First, you might check your data to see if there's more than one product with PID = 1.

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

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



回答4:


Store the variable to object type and assign the object type as datasource to grid




回答5:


I think you have to do ToList() when to add to 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: As it is a GridView, has to take n number of rows. No row limit.




回答6:


I solve like this:

ProductDBEntities ctx = new ProductDBEntities ();
var q1 = ctx.Products.Where(x => x.PID == 1).ToList();
GridView1.DataSource = q1;
GridView1.DataBind();

I try it. It's work.



来源:https://stackoverflow.com/questions/5869033/how-to-bind-gridview-using-linq-entity-framework

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!