开发者

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;
        dg开发者_如何转开发CompletedRequests.DataBind();
    }


You should bind to a DataView instead:

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


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜