Loop table columns and delete

i want to loop through a datarow and it the value is 0 i would like to delete that column.

i have got so far but when i delete the column it causes a problem in the loop statement. i have come across this recently in another situation an i was told to loop backwards, but how can i do this when looping a list of columns.

my current code is;
        Dim dci As Integer = 0

        For Each c As DataColumn In ds.Tables("Grid").Columns
            If drw.Item(dci) = "0" Then
                ds.Tables("Grid").Columns.Remove(c)
            End If
            dci = dci + 1
        Next


thanks
MarcuswAsked:
Who is Participating?
 
Bob LearnedCommented:
Try this:

       Dim dci As Integer = 0
       Dim dt As DataTable = ds.Tables("Grid")
       For index As Integer = dt.Columns.Count - 1 To 0 Step -1
            Dim c As DataColumn = dt.Columns(index)
            If drw(c).ToString() = "0" Then
                dt.Columns.Remove(c)
            End If
            dci += 1
        Next

Bob
0
 
hongjunCommented:
Try

For i = ds.Tables("Grid").Columns.Count - 1 To 0
      If drw.Item(dci) = "0" Then
            ds.Tables("Grid").Columns.Remove(i)
      End If
      dci = dci + 1
Next
0
 
hongjunCommented:
Yes you will need the "Step -1".
I left it out.

hongjun
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.