korymiller
korymiller

Reputation: 357

Modifying DataTables C#

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

Upvotes: 1

Views: 168

Answers (3)

Anthony Pegram
Anthony Pegram

Reputation: 126804

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

Upvotes: 2

SLaks
SLaks

Reputation: 887275

You should bind to a DataView instead:

dgCompletedRequests.DataSource =
    new DataView(compDV.Table, "DateCompleted > #" + lastWeek + "#");

Upvotes: 4

Rockdocta
Rockdocta

Reputation: 614

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.

Upvotes: 0

Related Questions