asp.netwebusercontrol

How to get the value of TextBox (programmatically added) which is inside a user control (user control rendered inside Repeater)


Generally we do this to get the value of textbox which is inside a user control.

<asp:TextBox runat="server" Text="Test" ID="txtTest"/>

In code behind create a property

public string MyString
  {  
     get  { return txtTest.Text; }   
  }

And in parent page we can get the instance of user control and get the value of textbox like

foreach (RepeaterItem itm in rptAttribute.Items)
{     
 MyUserControl uc = ((MyUserControlitemUserControl)itm.FindControl("MyContorlName"));
 string  test = uc.MyString;
}

but not sure How to render the value if the Textbox in user control created Programmatically.


Solution

  • You can take a similar approach to your text box but declare a public method which takes the textbox name as a parameter and then returns it like this:

    In your ASCX:

    public TextBox GetDynamicTextBoxByID(string textBoxId)
    {
      return (TextBox)Page.FindControl(textBoxId);
    }
    

    In your Parent page:

    foreach (RepeaterItem itm in rptAttribute.Items)
    {     
     MyUserControl uc = ((MyUserControlitemUserControl)itm.FindControl("MyContorlName"));
     string  test = uc.MyString;
     TextBox tx = uc.GetDynamicTextBoxByID(idOfTextBox);
    }
    

    Don't forget to check for null being returned and handling appropriately.