无法将GridView绑定到LINQ to SQL结果 [英] Can't bind a GridView to a LINQ to SQL Result

查看:55
本文介绍了无法将GridView绑定到LINQ to SQL结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,我对LINQ完全陌生,并且在上周度过了我所能读到的一切.我只是在玩耍,尝试遵循我发现的一些示例(实际上是Scott Gu撰写的有关该主题的PDF),我完全不知所措.有人可以告诉我为什么,当我使用下面的代码将GridView绑定到下面的查询时,没有数据吗?我可以在调试时看到结果,因此我知道它们是从数据库返回的,显然它们并没有正确绑定.我读到一些东西说您不能直接绑定到结果,并且必须使用BindingSource作为中间步骤?

OK, I am amittedly new to LINQ and have spent the last week reading everything I could on it. I am just playing around, trying to follow some examples I have found (a PDF from Scott Gu on the topic, in fact) and I am at a complete loss. Can someone please tell me why, when I bind a GridView to the query below, using the code below, I get no data?? I can see the results while debugging, so I know they are coming back from the DB, they are just not apparently binding correctly. I read something saying you could not bind directly to the result,and that you have to use a BindingSource as an intermediate step?

有人,请告诉我我在这里想念的东西.

Someone, please tell me what I am missing here.

protected void Page_Load(object sender, EventArgs e)
{
    SwapDBDataContext db = new SwapDBDataContext();

    var users = from u in db.aspnet_Users
                select new
                {
                   Name =  u.UserName,
                   ID = u.UserId
                };

    GridView1.DataSource = users;
    GridView1.DataBind();

}

我只是使用一个空的GridView.我以为绑定将负责设置列以匹配查询中的结果列-这是一个愚蠢的初学者错误吗?

I am just using an empty GridView. I had assumed that the binding would take care of setting up the columns to match the resulting columns from the query - was that a stupid beginners mistake?

    <asp:GridView ID="GridView1" runat="server">
    </asp:GridView>

推荐答案

您不必转换为列表或数组.绑定至少需要IEnumerable T,这是您的Users变量.匿名类型只是编译器生成的具体类型的预编译占位符,因此您还应该能够绑定到匿名类型.

You should not have to convert to a List or Array. Binding requires, at a minimum, an IEnumerable<T>, which is what your Users variable is. Anonymous types are simply pre-compile place holders for compiler generated concrete types, so you should also be able to bind to anonymous types.

您的GridView可能没有设置AutoGeneratedColumns属性,这是使数据源定义显示哪些列所必需的.尝试启用它,然后查看GridView是否显示查询结果.

Your GridView may not have the AutoGeneratedColumns property set, which is what is required to have the data source define what columns appear. Try enabling that, and see if your GridView displays your queries results.

这篇关于无法将GridView绑定到LINQ to SQL结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆