Search code examples
c#mysqllinq

Lazy loading repeater has linq query not yielding results


So I'm lazy loading a repeater control:

The code to follow binds the repeater to the guestbookData property which is populated by loadGuestbook()

public partial class _Default
{
    private DataTable _guestbookData;
    public DataTable guestbookData
    {
        get
        {
            if (_guestbookData == null)
            {
                _guestbookData = loadGuestbook();
            }
            return _guestbookData;
        }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            DataBind();
        }
    }

    private DataTable loadGuestbook()
    {
        netguestData nd = new netguestData();
        List<post> data = nd.GetPosts(10, rptGuestbook.Items.Count);

        DataTable dt = new DataTable();
        // writing the list to a DataTable for bind happens here.
        // not sure how to cast IEnumerable to DataTable, else I'd do that

        return dt;
    }

    protected void btnLoadMore_Click(object sender, EventArgs e)
    {
        DataBind();
    }
}

The data is queried from the database with LINQ To SQL. Here's the GetPosts(int, int) function I'm using:

public class netguestData
{
    private netguestEntities ne = new netguestEntities();

    public netguestData()
    {

    }

    public List<post> GetPosts(int Take, int Skip)
    {
        var posts = (from p in ne.posts
                    .OrderByDescending(p => p.postdate)
                    .Take(Take)
                    .Skip(Skip)
                    select p).ToList();
        return posts;
    }
}

Now, to page this, I'm basically loading 10 rows per page and using the count of items in the repeater as reference for how many rows in the selected data to skip.

When the page loads for the first time, I get my initial 10 records without any problems, but when I click on the button to load the next set, it comes up blank.

The message in the debugger is:

Enumeration yielded no results

I've checked the Take and Skip values after the click and both are 10, as expected. There are over 200 rows in the table, so I can't understand what the problem is.

Can anyone suggest anything I can do to fix this?

Thanks in advance!


Solution

  • You probably want to Skip first then Take. (Doing the take first then the skip doesn't make much sense.)