youcef
youcef

Reputation: 11

using return in If Statement Vb.net

so i want to use a return in a If Statement thats return in a part of the code :( i want to check if the condition is valid in every DataGridView cells, so it will verify the first value if the condition not valid then it will check the second value without do any action. i hope thats clear

For i As Integer = 0 To DataGridView1.RowCount - 1
                    ' ruturn here !
                    If DataGridView1.Rows(i).Cells(6).Value = dt.Rows(0)(5) Then

                        DataGridView1.Rows(i).Cells(4).Value += 1
                    Else
                        If i = DataGridView1.RowCount - 1 Then
                            DataGridView1.Rows.Add(i + 1, dt.Rows(i)(0), dt.Rows(i)(1), dt.Rows(i)(2), qnt, dt.Rows(i)(4), dt.Rows(i)(5))
                        Else
                            Return 'return to scan the second row ( i = 1,2,3... etc)
                        End If
                    End If
                Next

Upvotes: 0

Views: 693

Answers (2)

OctaCode
OctaCode

Reputation: 645

Removing the second else will also do the job

For i As Integer = 0 To DataGridView1.RowCount - 1 
    If DataGridView1.Rows(i).Cells(6).Value = dt.Rows(0)(5) Then
    DataGridView1.Rows(i).Cells(4).Value += 1
Else If i = DataGridView1.RowCount - 1 Then
    DataGridView1.Rows.Add(i + 1, dt.Rows(i)(0), dt.Rows(i)(1), dt.Rows(i)(2), qnt, dt.Rows(i)(4), dt.Rows(i)(5)) 
    End If 
End If 
Next

While not exiting for manually the loop will continue anyway checking if i = DataGridView1.RowCount - 1

"Else continue for" doesn't do anything here

Upvotes: 1

Sebastian Brosch
Sebastian Brosch

Reputation: 43574

You need to use Continue For instead of Return. So your solution looks like the following:

For i As Integer = 0 To DataGridView1.RowCount - 1
    If DataGridView1.Rows(i).Cells(6).Value = dt.Rows(0)(5) Then
        DataGridView1.Rows(i).Cells(4).Value += 1
    Else
        If i = DataGridView1.RowCount - 1 Then
            DataGridView1.Rows.Add(i + 1, dt.Rows(i)(0), dt.Rows(i)(1), dt.Rows(i)(2), qnt, dt.Rows(i)(4), dt.Rows(i)(5))
        Else
            Continue For
        End If
    End If
Next

With Return you exit the whole Function or Sub. With Continue For you directly jump to the next item on the for loop without executing the code below the Continue For.

Upvotes: 2

Related Questions