Reputation: 131
I have this loop that pops out a message box every time the condition is true.
For i = 0 To DataGridView1.Rows.Count - 1
Dim c As Boolean
c = DataGridView1.Rows(i).Cells(0).Value
If c = True Then
cmd3.Connection = con
con.Open()
cmd3.CommandText = "insert into student select * from stud where studentno = '" & DataGridView1.Rows(i).Cells(1).Value.ToString & "' delete from stud where studentno = '" & DataGridView1.Rows(i).Cells(1).Value.ToString & "'"
dr3 = cmd3.ExecuteReader()
MessageBox.Show("Account approved.")
con.Close()
Else
End If
Next
The messagebox shows as many times as the checked row. And I want to show it just once. I relocate my messagebox everywhere but it does not work. I searched but did not come up for an answer. I tried moving it outside the loop but the problem is, the message box still shows even the condition is false.
Thanks!
Upvotes: 1
Views: 1982
Reputation: 575
One approach would be to create a counter for successful approvals and another counter for unsuccessful approvals and display these after completing the loop. The counters are incremented in the loop depending on the result of the boolean c in each iteration.
Dim iSuccessCount As Integer
Dim iFailedCount As Integer
For i = 0 To DataGridView1.Rows.Count - 1
Dim c As Boolean
c = DataGridView1.Rows(i).Cells(0).Value
If c = True Then
iSuccessCount +=1
cmd3.Connection = con
con.Open()
cmd3.CommandText = "insert into student select * from stud where studentno = '" & DataGridView1.Rows(i).Cells(1).Value.ToString & "' delete from stud where studentno = '" & DataGridView1.Rows(i).Cells(1).Value.ToString & "'"
dr3 = cmd3.ExecuteReader()
con.Close()
Else
iFailedCount += 1
End If
Next
Dim sb As New StringBuilder
sb.Append(iSuccessCount.ToString)
sb.Append(If(iSuccessCount = 1, " account was ", " accounts were "))
sb.Append("approved.")
sb.Append(Environment.NewLine)
sb.Append(iFailedCount.ToString)
sb.Append(If(iFailedCount = 1, " account was ", " accounts were "))
sb.Append("not approved.")
MessageBox.Show(sb.ToString)
Upvotes: 1