1

I have a list of data in a data table, I also have a button that when clicked Will Show the Rows that have been completed in the last week.

However, I cant get the table to update after the modifications for some reason

I get the date of 7 days ago, and for every row that has a completed date greater than it in the source DataTable, I delete that row. That should leave me with only rows completed in the last week, but for some reason every row remains after my method is done. Can anyone spot a problem here?

Thanks in advance for any help!

protected void btnShowLastWeek_OnClick(Object sender, EventArgs e)
    {
        DateTime current = DateTime.Today;
        DateTime lastWeek = current.AddDays(-7);

        DataTable temp = compDV.Table;

        for(int i = 0; i < temp.Rows.Count; i ++)
        {
            DateTime completed = (DateTime)temp.Rows[i]["DateCompleted"];

            if (completed.CompareTo(lastWeek.Date) <= 0)
            {
                temp.Rows.RemoveAt(i);
            }
        }

        dgCompletedRequests.DataSource = temp;
        dgCompletedRequests.DataBind();
    }
2
  • 1
    You need to loop over the table backwards, or you'll end up skipping some indices. Commented May 11, 2011 at 20:49
  • 1
    What happens if you step through the method in the debugger? Commented May 11, 2011 at 20:50

3 Answers 3

4

You should bind to a DataView instead:

dgCompletedRequests.DataSource =
    new DataView(compDV.Table, "DateCompleted > #" + lastWeek + "#");
Sign up to request clarification or add additional context in comments.

Comments

2

I would follow SLaks' advice from the comments, but when it comes down to it, I would also consider punting and just rewrite the code to query the datatable without modifying the original.

dgCompletedRequests.DataSource = 
      temp.AsEnumerable()
          .Where(row => row.Field<Datetime>("DateCompleted") >= lastWeek)
          .AsDataView(); // or .CopyToDataTable(); if you need it

4 Comments

Except that that won't bind correctly. blog.slaks.net/2011/01/binding-to-lists-of-datarows.html
@SLaks, interesting, and it makes sense.
AsDataView() would be faster.
Thank you Anthony and SLaks! You both have been very helpful!
0

Was dgCompletedRequests.DataSource already set before this code executes? I'm not sure if this will work for you but it has for me in the past, you might give this a try. Set your dgCompletedRequests.DataSource = null; then set it to temp after. Somehow I think this will "reset" the databinding.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.