Programatically create multiple textboxes in windows application
In this code snippet we will see how to create TextBox Windwos controls dynamically. In code-snippet, we will see that how you can create multiple textboxes programatically in single event of Windows Forms Application. It is very simple to do this task. You just have to create simple form and set your form size and define the number of buttons that you want to add in form and click on button, textboxes will be automatically added to different positions.
Step 1:
Create one form
Step 2:
Write the below code on Button Click Event or on Any Control's Event
// I had written this code on Button Click Event.
C# Code :
private void ButtonGenerateTextBox_Click(System.Object sender, System.EventArgs e)
{
int n = 5; // define here how many textboxes you want to generate
TextBox[] textBoxes = new TextBox[n];
for (int i = 0; i <= n - 1; i++)
{
textBoxes(i) = new TextBox();
}
for (int i = 0; i <= n - 1; i++)
{
textBoxes(i).Name = "txt" + this.Controls.Count.ToString();
textBoxes(i).Visible = true;
textBoxes(i).Text = textBoxes(i).Name;
switch (i) {
case 0:
textBoxes(i).Location = new Point(100, 50);
break;
case 1:
textBoxes(i).Location = new Point(100, 100);
break;
case 2:
textBoxes(i).Location = new Point(100, 150);
break;
case 3:
textBoxes(i).Location = new Point(100, 200);
break;
case 4:
textBoxes(i).Location = new Point(100, 250);
break;
}
this.Controls.Add(textBoxes(i));
// add it to form's control collection.
this.Refresh();
}
}
VB Code :
Private Sub ButtonGenerateTextBox_Click(sender As System.Object, e As System.EventArgs)
Dim n As Integer = 5 // define here how many textboxes you want to generate
Dim textBoxes As TextBox() = New TextBox(n - 1) {}
For i As Integer = 0 To n - 1
textBoxes(i) = New TextBox()
Next
For i As Integer = 0 To n - 1
textBoxes(i).Name = "txt" + Me.Controls.Count.ToString()
textBoxes(i).Visible = True
textBoxes(i).Text = textBoxes(i).Name
Select Case i
Case 0
textBoxes(i).Location = New Point(100, 50)
Exit Select
Case 1
textBoxes(i).Location = New Point(100, 100)
Exit Select
Case 2
textBoxes(i).Location = New Point(100, 150)
Exit Select
Case 3
textBoxes(i).Location = New Point(100, 200)
Exit Select
Case 4
textBoxes(i).Location = New Point(100, 250)
Exit Select
End Select
Me.Controls.Add(textBoxes(i))
// add it to form's control collection.
Me.Refresh()
Next
End Sub
// Now your textboxes will be generated at different different positions based on case value.