天下無雙
阿龍 --质量是流程决定的。

I have been doing a lot of web service work for my job lately.  I am getting data back from application and returning it to PeopleSoft.  I ran into a small issue when trying to setup a new DataSet.  I wanted to include only certain rows of data from one of the tables that I was getting back in the DataSet that the web application, which I am integrating into our online system, was returning.

The line of code that I was using to add the DataTable to my DataSet was quite simple...

dtNewData.Tables.Add( dsAppData.Tables[0] );

Almost immediately, I found that was causing a real problem.  I kept getting an error that said “DataTable already belongs to another DataSet”.  I did some searching on Google and finally found that you cannot simply add a table to a DataSet that already exists in another DataSet.  Luckily, there are ways around this.

The most simple way to get around this issue is to make a copy of the table before adding.  This is achieved with a very simple change to the line of code above:

dtNewData.Tables.Add( dsAppData.Tables[0].Copy() );

Unfortunately, this did not meet my needs, because I only need the first few rows of data from the original table.  My final code ended up looking like this:

dtNewData = dsAppData.DataSet.Copy();
while (dsAppData.Tables[0].Rows.Count > RequestedRows)
{
     DataRow dr = dsAppData.Tables[0].Rows[dsAppData.Tables[0].Rows.Count-1];
     dsNewData.Tables[0].Rows.Remove(dr);
}

This created a copy of the entire DataSet and just removes the unwanted rows at the end of the table.  Originally, I did a clone of the table and used ImportRow(), but this method seems to be just a little faster.

posted on 2009-03-30 15:00  阿龍  阅读(324)  评论(0编辑  收藏  举报