Click here to Skip to main content
15,888,454 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
How to create many labels and textboxes dynamically depending on the value of an integer variable?


Is there any way to dynamically create and display 'n' Labels with 'n' corresponding Textboxs when we know value of 'n' after for example, clicking "Display" button.

Let me know if anything make you don't understand my question. Thank you!

I am working with VS C# Express 2010 Windows Form.
Posted
Comments
[no name] 23-Oct-14 3:35am    
did u try ?... if you try where you struck ? let us know
BillWoodruff 23-Oct-14 5:46am    
I assume that there is a "relationship" between Label and TextBox,: that probably you want each Label to inform the user what the TextBox created with it is for, and to have a certain relationship in terms of position (to the right, left, above, below) to the TextBox ...

Is that correct ? Do you have code now that handles the positioning of the Labels and TextBoxes ? Or, are you putting them in some ContainerControl that positions them for you, like a FlowLayoutPanel ?

Is it the case that you will need to create Labels/TextBoxes more than once at run-time ?

You need to do that in run time.

Suppose you have a windows form, and for n you want to create n labels and textboxes.
Now you can do:

for (int i=0;i<n;i++){>
Label label =new Label(){ Text = "WHATEVER"};
Textbox textBox= new Textbox(){Text = ""};

//Now add to the form directly, if you want to add to some container then thats ok just //place them where ever you want.
yourForm.Controls.Add(label);
yourForm.Controls.Add(textBox);
}
 
Share this answer
 
try this....
C#
int n = 4; // Or whatever value - n has to be global so that the event handler can access it

private void btnDisplay_Click(object sender, EventArgs e)
{
  TextBox[] textBoxes = new TextBox[n];
  Labels[] labels = new Labels[n];

  for (int i = 0; i < n; i++)
  {
    textBoxes[i] = new TextBox();
    // Here you can modify the value of the textbox which is at textBoxes[i]

    labels[i] = new Label();
    // Here you can modify the value of the label which is at labels[i]
  }

  // This adds the controls to the form (you will need to specify thier co-ordinates etc. first)
  for (int i = 0; i < n; i++)
  {
    this.Controls.Add(textBoxes[i]);
    this.Controls.Add(labels[i]);
  }
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900