简体   繁体   中英

How to manipulate controls created at runtime?

Suppose I have this in page load:

Label lblc = new Label();

for (int i = 1; i <= 10; i++)
{
    lblc.Text = i.ToString();
    this.Controls.Add(lblc);
}

How can I manipulate each of these controls at run time?

I want to:

  • Set/get their text.

  • Reference a particular control, in this case Label.

Use an array if you know how many labels you will have,

Label[] lblc = new Label[10];

for (int i = 0; i < 10; i++)
{
    lblc[i] = new Label() { Text = (i + 1).ToString() };
    this.Controls.Add(lblc[i]);
}

Then you will reference the textbox 1 with lblc[0] and textbox 2 with lblc[1] and so on. Alternatively if you do not know how many labels you will have you can always use something like this.

List<Label> lblc = new List<Label>();
for (int i = 0; i < 10; i++)
{
    lblc.Add(new Label() { Text = (i + 1).ToString() });
    this.Controls.Add(lblc[i]);
}

You reference it the same way as the array just make sure you declare the List or the array outside your method so you have scope throughout your program.

Suppose you want to do TextBoxes as well as Labels well then to track all your controls you can do it through the same list, take this example where each Label has its own pet TextBox

List<Control> controlList = new List<Control>();
        for (int i = 0; i < 10; i++)
        {
            control.Add(new Label() { Text = control.Count.ToString() });
            this.Controls.Add(control[control.Count - 1]);
            control.Add(new TextBox() { Text = control.Count.ToString() });
            this.Controls.Add(control[control.Count - 1]);
        }

Good luck! Anything else that needs to be added just ask.

Better to set the Name and then use that to distinguese between the controls

for (int i = 1; i <= 10; i++)
{
    Label lblc = new Label();
    lblc.Name = "lbl_"+i.ToString();
    lblc.Text = i.ToString();
    this.Controls.Add(lblc);
}

when:

public void SetTextOnControlName(string name, string newText)
{
  var ctrl = Controls.First(c => c.Name == name);
  ctrl.Text = newTExt;
}

Usage:

SetTextOnControlName("lbl_2", "yeah :D new text is awsome");

Your code creates only one control. Because, label object creation is in outside the loop. you can use like follows,

for (int i = 1; i <= 10; i++)
{
    Label lblc = new Label();
    lblc.Text = i.ToString();
    lblc.Name = "Test" + i.ToString(); //Name used to differentiate the control from others.
    this.Controls.Add(lblc);
}
//To Enumerate added controls
foreach(Label lbl in this.Controls.OfType<Label>())
{
    .....
    .....
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM