views:

42

answers:

3

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, ... or 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();
+1  A: 

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).

Marc Gravell
+1  A: 

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.

Thorsten Dittmar
+1  A: 

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.

Mark