Dot-Net

在 VB.NET 中檢查空的 TextBox 控制項

  • September 4, 2017

我在 VB.NET 中有一個表單應用程序。

我在一個表單上有很多文本框(大約 20 個)。無論如何要一次檢查它們是否為空,而不是寫出大量程式碼來單獨檢查每個,例如

If txt1.text = "" Or txt2.text="" Then
   msgbox("Please fill in all boxes")

這似乎是一個很長的路要走?

你也可以使用 LINQ:

Dim empty =
   Me.Controls.OfType(Of TextBox)().Where(Function(txt) txt.Text.Length = 0)
If empty.Any Then
   MessageBox.Show(String.Format("Please fill following textboxes: {0}",
                   String.Join(",", empty.Select(Function(txt) txt.Name))))
End If

有趣的方法是Enumerable.OfType

查詢語法相同(在 VB.NET 中更易讀):

Dim emptyTextBoxes =
   From txt In Me.Controls.OfType(Of TextBox)()
   Where txt.Text.Length = 0
   Select txt.Name
If emptyTextBoxes.Any Then
   MessageBox.Show(String.Format("Please fill following textboxes: {0}",
                   String.Join(",", emptyTextBoxes)))
End If

引用自:https://stackoverflow.com/questions/9489671