How to get the Name Of Multiple TextBoxes Using For Each Loop

In this tutorial I will teach you how to get the name of a specific TextBoxes by using For Each Loop in VB.Net. This method will determine what are the names of your TextBoxes that you drag it on the Form. You will be able to find out the specific name of the TextBox because it will be seen in each TextBoxes. So let’s begin: Open Visual Studio and create a new Project. Drag all the TextBoxes and a Button. Then, do the Form just like this. First Form GetNames Double click the Button to fire the click event handler in the Method. Now, create a variable that represents the control.
  1. Dim txt As Control
After that, Loop the control that you have created.
  1.   For Each txt In Me.Controls
  2.  
  3.   Next
Then, check if the type of the control is a Textbox and if it’s true, then perform the process that puts the name of the TextBox to itself. Do this code inside the Loop.
  1.  
  2.  If txt.GetType Is GetType(TextBox) Then
  3.        txt.Text = txt.Name
  4.   End If
And here are the codes that we made.
  1. Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
  2.         Dim txt As Control
  3.         For Each txt In Me.Controls
  4.             If txt.GetType Is GetType(TextBox) Then
  5.                 txt.Text = txt.Name
  6.             End If
  7.         Next
  8.     End Sub
Press F5 to run your project and click the Button to fire the code in the method.

Add new comment