Results 1 to 5 of 5

Thread: Looping through controls looking for nulls

  1. #1

    Thread Starter
    Hyperactive Member
    Join Date
    Apr 2003
    Location
    Three Rivers, MI
    Posts
    354

    Looping through controls looking for nulls

    I have a form with 15 text boxes on it. I am looking for an efficient way to loop through all the text boxes looking for nulls before I commit a DB transaction.

    I know I can do a series of IF Thens but there has to be a better way. I assume there is a way to loop through the controls so I am looking for a sample that will help me et started. Also is it possible to send the focus to the first textbox error found in the loop?
    Last edited by BukHix; Nov 6th, 2003 at 01:24 PM.

  2. #2
    Your Ad Here! Edneeis's Avatar
    Join Date
    Feb 2000
    Location
    Moreno Valley, CA (SoCal)
    Posts
    7,339
    This will loop through all the textboxes on the form itself (not on another container that is on the form):
    VB Code:
    1. For Each txt As TextBox In Me.Controls
    2.   If txt.Text=String.Empty Then DoSomething
    3. Next

  3. #3

    Thread Starter
    Hyperactive Member
    Join Date
    Apr 2003
    Location
    Three Rivers, MI
    Posts
    354
    Hmmm am I missing something?
    Code:
           Dim txty As TextBox
            For Each txty In Me.Controls
                If txty.Text = String.Empty Then MsgBox("OOPS")
                Exit Sub
            Next
    Gives me this error

    An unhandled exception of type 'System.InvalidCastException' occurred in RP_6.0.exe

    Additional information: Specified cast is not valid.


    It then highlights this line For Each txty In Me.Controls. It does this regarless of whether I alter it as I did in my post or use it exactly like you posted it.
    Last edited by BukHix; Nov 6th, 2003 at 02:25 PM.

  4. #4
    Your Ad Here! Edneeis's Avatar
    Join Date
    Feb 2000
    Location
    Moreno Valley, CA (SoCal)
    Posts
    7,339
    Do you have Option Strict on? Try this:
    VB Code:
    1. Dim ctrl As Control
    2.         For Each ctrl In Me.Controls
    3.             If typeof ctrl Is Textbox AndAlso DirectCast(ctrl,TextBox).Text=String.Empty Then
    4.                   MsgBox("OOPS")
    5.                   Return
    6.             End If
    7.         Next

  5. #5

    Thread Starter
    Hyperactive Member
    Join Date
    Apr 2003
    Location
    Three Rivers, MI
    Posts
    354
    Thanks Edneeis that did the trick.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width