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

StackOverflow https://stackoverflow.com/questions/16202035

  •  11-04-2022
  •  | 
  •  

Frage

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.

War es hilfreich?

Lösung

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.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top