代码未按空控件

时间:2018-04-13 21:55:25

标签: vb.net visual-studio

我刚刚开始学习visual basic,我正在使用visual studio 2015。

我有一个员工数据库表单,用户必须在其中输入员工的所有详细信息。如果有任何字段留空,则会提示消息框。

我也附上了我的表格。

enter image description here

这是我的代码:

Sub blankdataentry()
    'Declaring the Variables
    Dim ctrl As Control

    'Enable the Data Entry Controls
    For Each ctrl In Me.Controls
        If TypeOf ctrl Is ComboBox Then
            If ctrl.Text = "" Then
                MsgBox("The Field " & ctrl.Name + " is Empty." & vbNewLine & "Please fill in the Relevant Information.", vbInformation, "Missing Details")
                ctrl.Focus()
                Exit Sub
            End If
        ElseIf TypeOf ctrl Is MetroFramework.Controls.MetroTextBox Then
            If ctrl.Text = "" Then
                MsgBox("The Field " & ctrl.Name + " is Empty." & vbNewLine & "Please fill in the Relevant Information.", vbInformation, "Missing Details")
                ctrl.Focus()
                Exit Sub
            End If
        End If
    Next
End Sub

我在保存按钮上调用此功能。 当我单击保存按钮时,它忽略了我的文本框的顺序并随机检查文本框并显示带有其名称的消息。

例如,如果我没有输入任何信息并按下保存按钮,它应该提示我输入员工ID,但它会将我带到“加油”文本框。

请查看并告知我该如何解决此问题。

感谢。

3 个答案:

答案 0 :(得分:2)

您可以按升序[0,1,2,...等] 设置控件的TabIndex property,这有助于您设置控件的Tab键顺序。现在,既然你想按顺序检查控件,那么使用Tab键顺序迭代它们是完全合理的。

然后你可以用以下代码简单地替换你的循环:

For Each ctrl In Me.Controls.OfType(Of Control).
                             OrderBy(Function(c) c.TabIndex)
    ' Do whatever you want with the controls as they
    ' are now in the same order of the TabIndex property.
Next

希望有所帮助。

答案 1 :(得分:1)

您可以通过访问设计器创建的生成代码来直接更改Controls集合中控件的顺序。右键单击Form1.Designer.vb并选择View Code。向下滚动到控件添加到Controls集合的位置。现在剪切并粘贴到所需的顺序。要非常小心,因为你真的不应该惹这个。

Me.Controls.Add(Me.TextBox1)
 Me.Controls.Add(Me.Button1)
 Me.Controls.Add(Me.TextBox4)
 Me.Controls.Add(Me.TextBox3)
 Me.Controls.Add(Me.TextBox2)

答案 2 :(得分:0)

列出消息,以便他们看到所有消息。

这将只选择一个控件,但用户将知道所有控件都需要同时进行编辑。

Function ValidDataEntry() as Boolean
    'Declaring the Variables
    Dim messages as New List(Of String)

    'Enable the Data Entry Controls
    For Each ctrl As Control In Me.Controls
        If TypeOf ctrl Is ComboBox Then
            If ctrl.Text = "" Then
                messages.Add("The Field " & ctrl.Name + " is Empty.")
                If messages.Count = 1 Then ctrl.Focus()
                'Exit Sub
            End If
        ElseIf TypeOf ctrl Is MetroFramework.Controls.MetroTextBox Then
            If ctrl.Text = "" Then
                messages.Add("The Field " & ctrl.Name + " is Empty.")
                If messages.Count = 1 Then ctrl.Focus()
                'Exit Sub
            End If
        End If
    Next

    If messages.Count > 0 Then


        System.Windows.Forms.MessageBox.Show( _
            String.Join(Environment.NewLine, _
            messages.ToArray()), "Please fill in the Relevant Information.") 
     End If

     Return messages.Count = 0
End Function