Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Remove a row from a dataset and move other rows up 1

Status
Not open for further replies.

july07

Programmer
Aug 26, 2009
33
US
Hello,

I tried to remove a row from a dataset while looping through the dataset, but it seems other rows are not moving up. I am getting an error message "IndexOutofRange Exception was unhandeled, There is no row at position 21." and i have 30 rows in the dataset.

Here is the code and what i tried to do:
Code:
 Dim I As Integer
        For I = 1 To ds.Tables(0).Rows.Count - 1
            If IDnumber = 5
                ds.Tables(0).Rows.RemoveAt(I)
            Else
            End if
        Next

Once it removes the row and moves to the next row, i get the error message. Does any one know why i am getting this error?

Thanks
 

You're getting the error because the row *is* moving up, which changes the remaining indices of the datatable. To do what you want, loop through the rows in reverse order, so any changes will only affect rows that have already been processed:

For I As Integer = ds.Tables(0).Rows.Count - 1 To 0 Step -1
If IDnumber = 5
ds.Tables(0).Rows.RemoveAt(I)
End if
Next

I used to rock and roll every night and party every day. Then it was every other day. Now I'm lucky if I can find 30 minutes a week in which to get funky. - Homer Simpson

Arrrr, mateys! Ye needs ta be preparin' yerselves fer Talk Like a Pirate Day!
 
Thanks Jebeson,

I have to loop starting from the first row to the last row, because i need the rows to be in order, based on time. if i start from the bottom like you suggested, it wouldn't help what i am trying to accomplish.

Is there another way i can start from the first row to the last row and still not get an error?

Thanks
 



Please explain what you are trying to accomplish, that cannot be done in the reverse order.

Skip,
[sub]
[glasses]Just traded in my old subtlety...
for a NUANCE![tongue][/sub]
 

Sort your data by time, in reverse order. Then when you loop through the rows in reverse order, you will be starting at the earliest and progressing to the latest.

I used to rock and roll every night and party every day. Then it was every other day. Now I'm lucky if I can find 30 minutes a week in which to get funky. - Homer Simpson

Arrrr, mateys! Ye needs ta be preparin' yerselves fer Talk Like a Pirate Day!
 
Thanks i was able to loop in reverse order and accomplish what i am trying to do.

Thanks for the help
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top