Nested Loop for DataGridView not working as expected...

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Andrew Badura
    New Member
    • Dec 2010
    • 1

    Nested Loop for DataGridView not working as expected...

    Code:
                Dim cv As Integer
                Dim cc As Integer
                Dim CurrentValue As Double
                Dim ObsoleteValue As Double
                Dim Ans As Double
    
                For cc = 0 To DataGridView1.Columns.Count
                    For cv = 1 To DataGridView1.Rows.Count
                        CurrentValue = DataGridView1.Rows.Item(cv).Cells(cc).Value
                        ObsoleteValue = DataGridView1.Rows.Item(cv - 1).Cells(cc).Value
                        Ans = ((CurrentValue / ObsoleteValue) - 1) * 100
                        TextBox1.Text += Ans.ToString & vbTab & cc & vbNewLine
                    Next
                Next
    Basically this code works for the first column of the DataGridView. It sort of stops iterating after the last calculation of the row is performed and doesn't change the cc value at all. Meaning the loop gets stuck after the first iteration. If anyone can help me with this, I'd really appreciate it!
  • David Gluth
    New Member
    • Oct 2010
    • 46

    #2
    This code looks like it would end in an invalid index to me. Column and row counts are 0 based but ‘count’ is not.
    Therefore your code need to be “…count -1” to execute properly.
    Code:
    For cc = 0 To DataGridView1.Columns.Count - 1
                For cv = 1 To DataGridView1.Rows.Count - 1
                    CurrentValue = DataGridView1.Rows.Item(cv).Cells(cc).Value
                    ObsoleteValue = DataGridView1.Rows.Item(cv - 1).Cells(cc).Value
                    Ans = ((CurrentValue / ObsoleteValue) - 1) * 100
                    TextBox1.Text += Ans.ToString & vbTab & cc & vbNewLine
                Next
            Next

    Comment

    Working...