如何使用LINQ查询中的单个对象填充GridView?

时间:2015-11-29 14:24:02

标签: c# asp.net linq gridview

我知道如何用一组实例填充GridView。

 var newReviews = from r in myEntities.Reviews
                                     orderby r.Id
                                     select r;
            GridView1.DataSource = newReviews.ToList();
            GridView1.DataBind();

如何只检索GridView中的单个实例:

 var newReviews = (from r in myEntities.Reviews
                                     orderby r.Id
                                     select r).Single();
         ....

3 个答案:

答案 0 :(得分:0)

创建一个包含一个元素的数组:

var newReviews = (from r in myEntities.Reviews
                  orderby r.Id
                  select r).Single();

GridView1.DataSource = new[]{ newReviews;}
GridView1.DataBind();

答案 1 :(得分:0)

试试这个:

var newReviews = (from r in myEntities.Reviews
                                 orderby r.Id
                                 select r).FirstOrDefault();
if(newReviews != null)
{
    var tempList = new List<dynamic>();
    tempList.Add(newReviews);
    GridView1.DataSource = tempList;
    GridView1.DataBind();
}

答案 2 :(得分:0)

另一种方法是使用LINQ方法Take()

var newReviews = from r in myEntities.Reviews
                                 orderby r.Id
                                 select r;
        GridView1.DataSource = newReviews.Take(1).ToList();
        GridView1.DataBind();