Find first empty textbox on form

Bozz

Member
Joined
Jul 28, 2009
Messages
14
Programming Experience
Beginner
I'm using the following code to set the cursor automatically (important) to the first empty textbox on my form:
Private Sub FirstEmptyBox()
If TextBox1.Text = "" Then
TextBox1.Select()
Exit Sub
End If
If TextBox2.Text = "" Then
TextBox2.Select()
Exit Sub
End If
If TextBox3.Text = "" Then
TextBox3.Select()
Exit Sub
End If
'(Etc. Etc. You get the picture.)
End Sub
Works great! The problem is that I have 14 zillion textboxes, and I don't want to get carpal tunnel syndrome.
Any help please?
 
This should do it: (Use the nested For Each child block only if you have more textboxes inside of containers, such as group boxes.)


VB.NET:
	Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
		For Each ctl As Control In Controls
			If TypeOf ctl Is TextBox AndAlso ctl.Text = "" Then
				ctl.Focus()
			End If
			For Each child As Control In ctl.Controls
				If TypeOf child Is TextBox AndAlso child.Text = "" Then
					child.Focus()
				End If
			Next child
		Next ctl
	End Sub
 
Last edited:
Looping thru the controls like that, itterates them in an order from the last control placed on a form to the first control.
 
On my computer, it iterates in order of creation. Did you try it?

If you want to reverse the order, you can do this:


VB.NET:
	Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
		'Reverse order of control's TabIndex
		For ndx As Integer = 0 To Controls.Count
			For Each ctl As Control In Controls
				If TypeOf ctl Is TextBox AndAlso ctl.Text = "" AndAlso ctl.TabIndex = ndx Then
					ctl.Focus()
				End If
			Next ctl
		Next ndx
	End Sub
 
Thanks guys, and excellent work.
It reverses on my machine too, so I wound up using a reversed arraylist:

Private Sub FirstEmptyBox()
Dim MyArrayList As New ArrayList
For Each MyBox As TextBox In Me.Controls.OfType(Of TextBox)()
MyArrayList.Add(MyBox)
Next
MyArrayList.Reverse()
For Each Item As TextBox In MyArrayList
If Item.Text = "" Then
Item.Select()
Exit For
End If
Next
End Sub

Seems so simple now.
My fingers appreciate your help.
 
Last edited:
To iterate controls in TabIndex order regardless of container use the GetNextControl Method.
 
Improvment

Beat this guys:

Private Sub FirstEmptyBox()
For Each MyBox As TextBox In Controls.OfType(Of TextBox)().Reverse
If MyBox.Text = "" Then
MyBox.Select()
Exit For
End If
Next
End Sub
 
Back
Top