VB.NET 需要有关使用 MessageBox 检查错误的指南

VB.NET Need guide on error checking using MessageBox

假设我有一个包含 100 个文本框、组合框和其他控件的表单,我想检查是否有任何控件为空。当我单击 'OK' 按钮时,我希望消息框显示错误列表,例如 Textbox1 为空,Textbox30 为空等等。

我可以通过检查文本框 1 和显示消息框、检查文本框 2 和再次显示消息框等繁琐的方法来实现这一点。

我希望消息框只显示一次。我怎样才能做到这一点?

我所做的是设置一个数组并存储所有错误消息,稍后通过选择(示例 Msgbox(errMessages(3) + Environment.newline + errMessages(30))和我知道这也不是正确的方法。

请提前谢谢。

这是对您问题的直接回答:

您可以将空控件存储在列表中,最后创建如下消息:

Dim empty_controls = New List(Of Control)

If TextBox1.Text = String.Empty Then
    empty_controls.Add(TextBox1)
End If

If TextBox2.Text = String.Empty Then
    empty_controls.Add(TextBox2)
End If

Dim result As String = String.Join(
    Environment.NewLine,
    empty_controls.Select(Function(c As Control) c.Name + " is empty"))

MessageBox.Show(result)

这里有一个更好的方法来检测哪些文本框是空的:

Dim empty_controls = New List(Of Control)

//The following line will search through all text boxes on the form
empty_controls.AddRange(
    Controls.OfType(Of TextBox).Where(Function(c As Control) c.Text = String.Empty))

//Here you can add other kinds of controls with their own way of determining if they are empty

Dim result As String = String.Join(
    Environment.NewLine,
    empty_controls.Select(Function(c As Control) c.Name + " is empty"))

MessageBox.Show(result)