Linq – Can’t bind a GridView to a LINQ to SQL Result

linqlinq-to-sql

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();

}

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>

Best Answer

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.

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.