Looping through a row of data and deleting rows

I populated Datatable from two different servers. I can make corrections when my length is> 0, what I want to do is delete the lines that did not hit. Here is a summary of what I have

DataRow[] dr = payments.dtPayments.Select(myselect); if (dr.Length > 0) { for (int a = 0; a < dr.Length; a++) { if (thisOption == true) dr[0].Delete(); else if (otherOption == true) { dr[0]["Date"] = myDataReader["date"].ToString().Trim(); dr[0]["Pay"] = payTypeName(myDataReader["ccdsrc"].ToString() .Trim()); } } } if (dr.Length == 0) { if (LastOption == true) { //DataRow should be removed } } 
+7
c # sql
source share
5 answers

If dr.Length is zero, then your selection did not return any rows. If you want to delete rows that do not meet your criteria, I would execute this as another type of query. It is also possible that I do not fully understand your question. Could you please update your question to show your SQL and indicate where in the sample code you had a problem: inside the loop or after the loop, where do you have a comment?

+4
source share

I'm not sure I fully understand your question, but it seems like you are trying to remove an entry from the collection while you are still fixated on it. (which will result in an array index error)

You must save the link to each entry that you want to delete in the new collection, and then delete all new entries from the old collection:

 DataRow[] dr = payments.dtPayments.Select(myselect); List<DataRow> rowsToRemove = new List<DataRow>(); for (int a = 0; a < dr.Length; a++) { if(/* You want to delete this row */) { rowsToRemove.Add(dr[a]); } } foreach(var dr in rowsToRemove) { payments.dtPayments.Rows.Remove(dr); } 
+18
source share

You need to create a datarow outside the loop, and then when you get to the line you want to delete, assign it to the line you created outside. and break the loop. Then below the loop you can delete it.

 DataRow r = null; foreach(DataRow row in table.Rows) { if(condition==true) { r = row; break; } } table.Rows.Remove(r); 
+2
source share

Have you tried this?

payments.dtPayments.Rows.Remove (others)

+1
source share

You can scroll the collection in reverse order (for (int i = rows.length-1; x> -1; x--)) to delete multiple rows to make sure you don't get the index from related errors.

+1
source share

All Articles