在循环vb.net中仅显示消息框一次

时间:2016-11-06 14:52:33

标签: vb.net loops for-loop messagebox

每次条件为真时,我都会弹出一个消息框。

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

消息框显示与已检查行一样多的次数。我想只展示一次。我在任何地方重新定位我的消息框但它不起作用。我搜索但没有找到答案。 我试着把它移到循环外但问题是,消息框仍然显示条件是假的。

谢谢!

1 个答案:

答案 0 :(得分:1)

一种方法是创建一个成功批准的计数器和另一个不成功批准的计数器,并在完成循环后显示这些计数器。计数器在循环中递增,具体取决于每次迭代中布尔值c的结果。

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)