I'm trying to collect up a number of text boxes and test against what is entered. I know this has been answered several times but most cases want to collect all the controls in a panel or form, I want to choose each text box.
I'm trying this, based on another stack overflow answer Loop through textboxes in vb.net but it not working for me. Null reference exception, which presumably I've not instantiated my object but I have I not, with the new keyword.... In summary why does this not work?
Dim boxes As New List(Of TextBox)() From {TextBox1, TextBox2, TextBox3, TextBox4, TextBox5}
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
TestTextBox()
End Sub
Private Sub TestTextBox()
For Each tb As TextBox In boxes
If String.IsNullOrEmpty(tb.Text) Then
MessageBox.Show("Text box is empty")
ElseIf tb.Text.Length > 10 Then
MessageBox.Show("Characters limited to 10")
End If
Next
End Sub
CodePudding user response:
You get null
list objects in the loop because you create a class collection and initialize it to add controls that haven't been created nor initialized yet. The boxes
is created before the Form's constructor calls the InitializeComponent();
to create and initialize the hosted controls including the text boxes in question. So you need to wait for the controls to be created to access them.
Declare a List<TextBox>
:
Public Class YourForm
Private ReadOnly boxes As List(Of TextBox)
End Class
Then in the constructor, instantiate it and pass the elements:
Public Class YourForm
Private ReadOnly boxes As List(Of TextBox)
Sub New()
InitializeComponent()
boxes = New List(Of TextBox) From {TextBox1, TextBox2, TextBox3, TextBox4, TextBox5}
End Sub
End Class
Side note, you can set the MaxLength
property of the text boxes to be 10
and omit this ElseIf tb.Text.Length > 10 Then...