开发者

Change values of dynamically added controls in winform c#.net application, how to track dynamically added controls

I have added controls dynamically on runtime inside the rows of a tableLayoutpanel , the controls added are LABELS, LINKLABEL AND A PICTURE BOX.

Now , i want to change the value(Text Property) o开发者_JAVA技巧f these dynamically added controls(Labels, Linklabels) to some specified value, on a button click.

How do i do this? Please help with code.

Is there some kind of ID for these dynamically controls like we have in HTML.

Also , am trying to use this but all in vain...........

Control[] GettableLayoutPanelControls = new Control[11];

          GettableLayoutPanelControls =  tableLayoutPanel1.Controls.Find("Control Name", true) ;

             GettableLayoutPanelControls.SetValue("CHANGED VALUE ", 0); //this line gives error..........


Try something like this, which will add 11 new text boxes (or any other control you want):

int NumberOfTextBoxes = 11;
TextBox[] DynamicTextBoxes = new TextBox[NumberOfTextBoxes];
int ndx = 0;

while (ndx < NumberOfTextBoxes) 
{
    DynamicTextBoxes[ndx] = new TextBox();
    DynamicTextBoxes[ndx].Name = "TextBox" + ndx.ToString();
    // You can set TextBox value here:
    // DynamicTextBoxes[ndx].Text = "My Value";
    tableLayoutPanel1.Controls.Add(DynamicTextBoxes[ndx]);
    ndx++;
}

This will dynamically add Text Boxes to your TableLayout control. If you need to retreive them later:

foreach (Control c in TableLayoutPanel1.Controls)
{
    if (c is TextBox)
    {
        TextBox TextBoxControl = (TextBox)c;

        // This will modify the value of the 3rd text box we added
        if (TextBoxControl.Name.Equals("TextBox3"))      
            TextBoxControl.Text = "My Value";
    }
}


The most straightforward way to do this is to keep track of the dynamically created controls in a private field.

private Label _myLabel;
_myLabel = new Label();
myLabel.Text = "Hello World!";
tableLayoutPanel1.Controls.Add(myLabel);
// ... later in the button click handler ... //
myLabel.Text = "Goodbye Cruel World!";

Remember, Windows Forms is a stateful environment, unlike ASP.NET, so fields don't lose their values when the user interacts with the form.

ETA:

Label dynamic_label = new Label();
for(in i =0;i<6;i++){this.Controls.Add(dynamic_label);}

This code from your comment adds the SAME label 5 times. I don't think that's your intent. When you set the Text property they will all have the same text because they reference the same control. You can use my solution and declare

Label myLabel1, myLabel2, ..., myLabel5;

If you have so many that you're declaring them in a loop then I would store them in a Dictionary<string, Label> so that you don't have to search the array to find the correct one.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜