Hello masters,

I want to know how to check an empty textbox in the form.
I can check it by assign Text1.Text = "".
But i have many textbox in form.

Thank you in advance

Dani AI

Generated

Good start, — looping the form controls is the right idea. Two gaps to watch for: that loop only sees top-level controls (so TextBoxes inside Panels, GroupBoxes or TabPages are missed), and a string of spaces counts as non-empty. Below is a small, reusable helper that (1) finds TextBox controls recursively, (2) treats whitespace-only text as empty, and (3) focuses/highlights the empty boxes so the user can fix them.

' Collect all TextBox controls under a container (recurses into children)
Function GetAllTextBoxes(root As Control) As List(Of TextBox)
    Dim list As New List(Of TextBox)
    For Each c As Control In root.Controls
        If TypeOf c Is TextBox Then
            list.Add(DirectCast(c, TextBox))
        End If
        If c.HasChildren Then
            list.AddRange(GetAllTextBoxes(c))
        End If
    Next
    Return list
End Function

' Example usage: find empties, focus the first, and highlight them
Dim empties As New List(Of TextBox)
For Each tb As TextBox In GetAllTextBoxes(Me)
    If String.IsNullOrWhiteSpace(tb.Text) Then empties.Add(tb)
Next
If empties.Count > 0 Then
    empties(0).Focus()
    For Each tb As TextBox In empties
        tb.BackColor = Color.LightYellow
    Next
    MessageBox.Show(empties.Count.ToString() & " required field(s) are empty.")
End If

Tips: if you target older .NET remove String.IsNullOrWhiteSpace and use tb.Text Is Nothing OrElse tb.Text.Trim().Length = 0. To validate only some fields, set Tag = "req" in the designer and skip others in the loop. For better UX consider ErrorProvider instead of changing BackColor. This approach scales cleanly for forms with many controls and nested containers — useful for your case, .

Recommended Answers

All 2 Replies

Try this :

Dim ctrAs Control

For Each ctr In Me.Controls
   If TypeOf ctr Is TextBox Then
      If ctr.Text= vbNullString Then
         MsgBox "Textbox empty"

         ctr.SetFocus

         Exit Sub

      End If
  End If
Next ctr
commented: Excellent suggestions based on in depth knowledge of the language. +5
commented: It's a wonderful code sir :) +2

Thank you sir for wonderful code..

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.