|
-
Apr 27th, 2010, 06:14 PM
#1
Thread Starter
Hyperactive Member
Looping Tutorial
Hello Everyone:
Can anyone tell me of a good looping tutorial? I am interested in a double loop; I think that’s what it is called. Something like this
Loop 1
Do this 10 times
Do this
Loop 2
Do this 6 times
Do something else
End loop 2
Do something different
End loop 1
I hope this makes sense?
Thanks
Art W.
SLEEP: A Totally Inadequate Substation For Caffeine!
-
Apr 27th, 2010, 06:54 PM
#2
Re: Looping Tutorial
What you're talking about is called nesting, i.e. the inner loop is nested inside the outer loop. It's really no big deal. The inner loop works just like any other loop; it just happens to be inside a block that just happens to be a loop. Nested loops are most often used to traverse multi-dimensional data structures, e.g. the following code will visit every row of a DataGridView and then visit each cell in the current row:
vb.net Code:
For Each row As DataGridViewRow In Me.DataGridView1.Rows For Each cell As DataGridViewCell In row.Cells MessageBox.Show(cell.Value.ToString()) Next Next
That uses For Each loops, which are more natural in situations that suit them. You can also use For loops:
vb.net Code:
For rowIndex As Integer = 0 To Me.DataGridView1.RowCount - 1 For columnIndex As Integer = 0 To Me.DataGridView1.ColumnCount - 1 MessageBox.Show(Me.DataGridView1(columnIndex, rowIndex).Value.ToString()) Next Next
You can put whatever code you like inside either loop, but obviously you can only use variables that are in scope, e.g. you could only access the loop counter for the inner loop, i.e. cell or columnIndex, inside the inner loop.
-
Apr 27th, 2010, 07:00 PM
#3
Re: Looping Tutorial
I should also point out that the code snippets above will both traverse the data across and then down. This is the most natural way to read data in a DataGridView but not the only way. The For Each loop above results in easier-to-read code but does not adapt well to reading the data down and then across. In the case of the For loops, you simply have to reverse their positions and the data will be read by column then by row rather than by row and then by column:
vb.net Code:
For columnIndex As Integer = 0 To Me.DataGridView1.ColumnCount - 1 For rowIndex As Integer = 0 To Me.DataGridView1.RowCount - 1 MessageBox.Show(Me.DataGridView1(columnIndex, rowIndex).Value.ToString()) Next Next
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|