2
votes

I'm completely new to using LINQ to SQL (but familiar with LINQ to objects) and I'm curious why the following piece of code throws no exception or errors, but does not create a GridView and bind data to it.

This is in the Page_Load event of a webform:

ContactsDataContext db = new ContactsDataContext();
db.Contacts.Where(x => x.Phone.Length > 0);
GridView gv = new GridView();
gv.DataSource = db.Contacts;
gv.DataBind();

If I drag and drop and GridView in the designer and set the DataSource as LINQ to SQL it works as expected. Markup for LinqDataSource

<asp:LinqDataSource ID="LinqDataSource1" runat="server" 
ContextTypeName="LinqExample.ContactsDataContext" EntityTypeName="" 
TableName="Contacts">
</asp:LinqDataSource>

Contacts is the only table in the .dbml file. What am I missing?

2
You want to have the GridView in the aspx file and bind the data in the codebehind without asp:LinqDataSource? - Rudy
So no dynamically creating GridViews and binding them to LINQ queries? - wootscootinboogie
If you create it dynamically you still have to add it to the Response. So you want it to be both in the cs file? But if so, where in the html do you want the table with the data? - Rudy
@Rudy this is literally the first time that I've played with LINQ to SQL and tried to use it to bind data to a web form. This was mainly an exercise in "why doesn't this work like using a IDataReader object in that you can create a GridView dynamically and have it bind correctly. - wootscootinboogie
Rudy's point is valid; having created a new instance of a GridView, are you adding it to the page or a container on the page ? If not, it's never going to render. - sh1rts

2 Answers

3
votes

Call the ToList() of your query. Also, your filtering is incorrect. You need to set your filter to a variable. You can't just call Where(). As your code is now, you would be returning all the contact records in your table. Also, you need to add your GridView to a control already on the page.

ContactsDataContext db = new ContactsDataContext();
var filteredContacts = db.Contacts.Where(x => x.Phone.Length > 0);
GridView gv = new GridView();
gv.DataSource = filteredContacts.ToList();
gv.DataBind();
this.Controls.Add(gv);
0
votes

From the link below it looks like you need to create a function for your LINQ command that would return LIST type and then have that called:

 protected void Page_Load(object sender, EventArgs e)  
    {  
        if (!Page.IsPostBack)  
        {  
            gvitems.DataSource = GetItemsRecord();  
            gvitems.DataBind();  

        }  

    }  

    public List<ITEM> GetItemsRecord()  
    {  
        BindGridViewDataContext db = new BindGridViewDataContext();  
        var listitemsrecord = (from x in db.ITEMs select x).ToList<ITEM>();  
        return listitemsrecord;  

    }  

https://www.c-sharpcorner.com/UploadFile/70dbe6/how-to-bind-gridview-using-linq-to-sql/