locked
Dynamically Assign Values to Textboxes and Labels RRS feed

  • Question

  • User931778073 posted

    Hi all, suppose I have 6 textboxes and six labels, txtTextbox1 through txtTextbox6 and lblLabel1 through lblLabel6. I would like to use a loop to dynamically assign values to them but I am having difficulties. I tried to use arrays but the problem I have there is dynamially assigning values to textboxes and labels inside of an array. Any suggestions is grately appreciated, thanks.

    Sunday, September 23, 2012 8:17 AM

Answers

  • User71929859 posted

    Hello,

    I would like to use a loop to dynamically assign values to them but I am having difficulties.

    You can do it like this

    for(int i=1; i<7; i++)
    {
       TextBox tb = (TextBox)Page.FindControl("txtTextbox"+i);
       tb.Text = i;
    }
    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Sunday, September 23, 2012 10:03 AM
  • User1455999623 posted

    Hi,

    Check out the below code in which Adding dynamic Label and Textbox in an asp:Panel and retrieving the same and assigning the value to it.

    protected void Page_Load(object sender, EventArgs e)
            {
                //Adding dynamic control to (pnl) Panel Control
                for (int i = 1; i < 7; i++)
                {
                    TextBox tb = new TextBox();
                    tb.ID = "txtTextbox" + i.ToString();
                    Label lbl = new Label();
                    lbl.ID = "lblLabel" + i.ToString();
    
                    pnl.Controls.Add(lbl);
                    pnl.Controls.Add(tb);
                }
    
    
                //Retrieving dynamic control from (pnl) Panel Control
                for (int i = 1; i < 7; i++)
                {
                    Label lbl = pnl.FindControl("lblLabel" + i) as Label;
                    lbl.Text = "Label " + i.ToString();
    
                    TextBox tb = pnl.FindControl("txtTextbox" + i) as TextBox;
                    tb.Text = i.ToString();
                }
            }

    Reply if any issues.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Sunday, September 23, 2012 10:21 AM

All replies