Paul Edward Pagente Paul Edward Pagente - 2 months ago 13
Vb.net Question

Redundant Message for Each row in Datagridview

Whats wrong with my code?

If DataGridView1.Rows.Count = 0 Then
MsgBox("Nothing to save.")
Else
For Each row As DataGridViewRow In DataGridView1.Rows

If row.Cells(5).Value.ToString() = "" Then
row.Cells(0).Value = True

MsgBox("Please indicate your adjustment reason")
Else
final_save()
End If
Next

End If


I`m stopping the user to save data of some or all cells in 5th column of datagridview. The code above is working but the message repeats for every row empty that it finds

TYSM for future help

Answer

You're not exiting the loop. Try using Exit For. You should also only save if all rows pass the test.

       dim failed = false
       For Each row As DataGridViewRow In DataGridView1.Rows

            If row.Cells(5).Value.ToString() = "" Then
                row.Cells(0).Value = True

                MsgBox("Please indicate your adjustment reason")
                failed = true
                Exit for

            End If
        Next
        if not failed then final_save()