如何在消息框中将所有验证错误显示为列表

时间:2015-04-01 03:19:07

标签: vb.net

我的代码出现问题。我试图在消息框中显示所有验证错误。任何人都可以告诉我为什么我的错误中只有一个出现在框中?我尝试了几个解决方案并环顾四周,但我需要一些帮助。

Public Class Form1
Private Sub btnCalculate_Click(sender As Object, e As EventArgs) Handles btnCalculate.Click
    If Data_Validated_ok() = False Then Exit Sub


End Sub
Private Function Data_Validated_ok() As Boolean

    Dim intErrCount As Integer
    Dim strErrMessage As String = String.Empty
    Dim ctrlError As New Collection

    ' make sure Premium channel is selected

    If Me.lstPremium.SelectedIndex < 0 Then
        intErrCount = intErrCount + 1
        strErrMessage = intErrCount & ". Premium Channels is a required field." _
        & vbCrLf
        ctrlError.Add(lstPremium.SelectedIndex)
    End If
    ' make sure a customer type is selected in the Radioboxes

    If radBusiness.Checked = False And
                radResidential.Checked = False Then
        intErrCount = intErrCount + 1
        strErrMessage = intErrCount & ".Customer Type is a required field." _
         & vbCrLf
        ctrlError.Add(radBusiness.Checked, radResidential.Checked)
    End If

    ' make sure a business customer checks at least one option in the listbox

    If radBusiness.Checked = True And Me.lstConnections.SelectedIndex < 0 Then
        intErrCount = intErrCount + 1
        strErrMessage = intErrCount & ". Business Customers must select 1 or more Connection." _
        & vbCrLf
        ctrlError.Add(lstConnections.SelectedIndex)
    End If

    ' show all errors in a messagebox

    If intErrCount > 0 Then
        MessageBox.Show(strErrMessage, "Validation Rule(s)", MessageBoxButtons.OK, MessageBoxIcon.Information)
        Dim ctrl As Control
        ctrl = ctrlError.Item(1)
        ctrl.Focus()
        Return False
    Else
        Return True
    End If

End Function

1 个答案:

答案 0 :(得分:0)

如何将每个错误存储在List(Of String)中?您的变量ctrlError不存储控件,而是整数和布尔值 - 您应该在那里存在转换错误。

Private Function Data_Validated_ok() As Boolean
  Dim errorMsgs As New List(Of String)
' make sure Premium channel is selected

  If Me.lstPremium.SelectedIndex < 0 Then
     errorMsgs.Add("Premium Channels is a required field.")
  End If
' make sure a customer type is selected in the Radioboxes

  If radBusiness.Checked = False AndAlso
            radResidential.Checked = False Then
    errorMsgs.Add("Customer Type is a required field.")
  End If

' make sure a business customer checks at least one option in the listbox

  If radBusiness.Checked = True And Me.lstConnections.SelectedIndex < 0 Then
    errorMsgs.Add("Business Customers must select 1 or more Connection.")
  End If

' show all errors in a messagebox

  If errorMsgs.Count > 0 Then
    MessageBox.Show(String.Join(Environment.Newline, errorMsgs.ToArray), "Validation Rule(s)", MessageBoxButtons.OK, MessageBoxIcon.Information)
    Return False
  Else
    Return True
  End If

End Function