how to add more labels according to the later input?
-
21-12-2019 - |
Question
I don't know whether it is clear. I mean a form has an input textbox and a button. If I input 5 in the textbox and click on the button, the form will add 5 labels... The question is I don't know it is 5 or 4 or 3……before the code is running and the input.
I don't know how to add the labels and how to define or get their names in order to use them later in the code.
I am just learning windows applications development with VS using C#.... And also this is my first ask in stackoverflow please forgive me if it is not clear. Is there anybody can help me?
Solution
let's split your entire problem into few steps of understanding:
What basically down the line, you are asking, is to how to add controls dynamically in a winform, in your case the control is label, so wrap your label creating logic in a function like below:
protected Label CreateLabel(string Id, string text) { Label lbl = new Label(); lbl.Name = Id; lbl.Text = text; return lbl; }
Now you need to add as many labels as the number entered in a given textBox and upon a button click, so possibly something like below in button's click event:
protected void button_Clicked(object sender, EventArgs e) { //make sure nothing invalid string comes here int counter = Convert.ToInt32(txtCount.text); for(int i=0;i<counter;i++) { var lbl = CreateLabel("rand"+i, "Label" +i); container.Controls.Add(lbl);//container can be your form } }
Now the basic problem in winforms you will face, will be about the positioning of these dynamically added labels. The most simple way to go about it is to add your labels to winforms
FlowLayoutPanel
. It automatically aligns the controls. There are other layout controls available aswell. so do this :drag and drop a FlowLayoutPanel on your form and give it the name "container", rest assured
OTHER TIPS
For example:
for(var i=0; i<N; i++ ) {
var l= new Label();
l.Text = "some name #" + i.ToString();
l.Width = 200;
l.Location = new Point(30, 20);
parent.Controls.Add(l);
}
You can use this as:
Label[] arrLabel;
int num = 0;
int.TryParse(textBox1.Text, out num);
arrLabel = new Label[num];
for (int i = 0; i < num; i++)
{
arrLabel[i] = new Label();
arrLabel[i].Text = "Label #" + (i+1);
arrLabel[i].Width = 20;
arrLabel[i].Location = new Point(30+10*(i+1), 20);
this.Controls.Add(arrLabel[i]);
}