开发者

Problems removing rows from dataset in C#

开发者 https://www.devze.com 2023-01-14 18:49 出处:网络
I have this situation: I have to create a dataset that takes all data from another dataset. In some cases I have to remove some rows from each of the new dataset. When both foreach cycles are finished

I have this situation: I have to create a dataset that takes all data from another dataset. In some cases I have to remove some rows from each of the new dataset. When both foreach cycles are finished, both datasets are empty, even when finish only the first, the first dataset has some rows.

Any idea why, ... o开发者_开发问答r tell where I have code wrong.

Thnx in advance.

//Dataset comes as a parameter.    
DataSet dsFirst = ds;
DataSet dsSecond = ds;

foreach (DataRow dr in dsFirst.Tables[0].Select())
{
    int i = Convert.ToInt32(dr["ROWNUMBER"]);
    //merren vetem veprimet ATM qe jane bere para CoB
    if (i > x && i < y)
        dr.Delete();
    else
        dr["NOVATRANSAKCIJA"] = 0;//eshte derguar njehere, per rrjedhoje nuk do te dergohet sms
}
dsFirst.AcceptChanges();

foreach (DataRow dr1 in dsSecond.Tables[0].Select())
{
    int i = Convert.ToInt32(dr1["ROWNUMBER"]);
    //merren veprimet e sistemit dhe veprimet ATM te bera gjate CoB
    if (i < x || i > y)
        dr1.Delete();
    else
        dr1["NOVATRANSAKCIJA"] = 1;//nuk eshte derguar asnjehere, per rrjedhoje do te dergohet sms

}
dsSecond.AcceptChanges();


As Marc has already pointed out you are working here with reference type values so you are actually pointing with ds, dsFirst and dsSecond to the same dataset. You have to make a copy of your dataset to achieve what you want to do.

try

dsFirst = ds.Copy(); 
dsSecond = ds.Copy();

instead, which will clone the structure and copy the data.


You only have one data-set (from your code):

DataSet dsFirst = ds;
DataSet dsSecond = ds;

Copying the reference doesn't clone the data - it is just another reference to the same data-set. So you have simply removed all the data. You might look at the Clone() method (but note that copies the structure, but not the data).


As your code is now, dsFirst and dsSecond are not copies of the original dataset, but "point" to the same dataset!

To copy a dataset and remove the rows on the go, I'd do the following:

foreach (DataRow dr in ds.Tables[0].Rows)
{
    int i = Convert.ToInt32(dr["ROWNUMBER"]);
    if (i <= x || i >= y)
      dsFirst.Tables[0].ImportRow(row);
}

dsFirst must be a new dataset with one table with exactly the same columns as ds. This imports only those rows into dsFirst that meet the criteria for not being deleted.

You may be able to create a copy of ds that contains the respective tables and column definitions by using ds.Clone(), but I haven't tried that yet. Working with typed datasets saves you a lot of work here, as you can create as many instances as you want and all tables and columns are already defined.

0

精彩评论

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