By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
459,948 Members | 1,587 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 459,948 IT Pros & Developers. It's quick & easy.

Nested Loop for DataGridView not working as expected...

P: 1
Expand|Select|Wrap|Line Numbers
  1.             Dim cv As Integer
  2.             Dim cc As Integer
  3.             Dim CurrentValue As Double
  4.             Dim ObsoleteValue As Double
  5.             Dim Ans As Double
  6.  
  7.             For cc = 0 To DataGridView1.Columns.Count
  8.                 For cv = 1 To DataGridView1.Rows.Count
  9.                     CurrentValue = DataGridView1.Rows.Item(cv).Cells(cc).Value
  10.                     ObsoleteValue = DataGridView1.Rows.Item(cv - 1).Cells(cc).Value
  11.                     Ans = ((CurrentValue / ObsoleteValue) - 1) * 100
  12.                     TextBox1.Text += Ans.ToString & vbTab & cc & vbNewLine
  13.                 Next
  14.             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!
Dec 3 '10 #1
Share this Question
Share on Google+
1 Reply


P: 46
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.
Expand|Select|Wrap|Line Numbers
  1. For cc = 0 To DataGridView1.Columns.Count - 1
  2.             For cv = 1 To DataGridView1.Rows.Count - 1
  3.                 CurrentValue = DataGridView1.Rows.Item(cv).Cells(cc).Value
  4.                 ObsoleteValue = DataGridView1.Rows.Item(cv - 1).Cells(cc).Value
  5.                 Ans = ((CurrentValue / ObsoleteValue) - 1) * 100
  6.                 TextBox1.Text += Ans.ToString & vbTab & cc & vbNewLine
  7.             Next
  8.         Next
  9.  
Dec 4 '10 #2

Post your reply

Sign in to post your reply or Sign up for a free account.