The main problem dealing with dynamically created control is you need to reload them back in either Page Init or Page Load event.
FYI: We normally use either Panel or PlaceHolder to load controls instead of Body tag, so that we can style them easily.
ASPX
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="DemoWebForm.Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<asp:PlaceHolder runat="server" ID="PlaceHolder1" />
<asp:Button runat="server" ID="SubmitButton" Text="Submit" OnClick="SubmitButton_Click" />
<br />
Posted Value:
<asp:Label runat="server" ID="ResultLabel" />
</form>
</body>
</html>
Code Behind
public partial class Default : System.Web.UI.Page
{
protected void Page_Init(object sender, EventArgs e)
{
HtmlGenericControl testes = new HtmlGenericControl("DIV");
testes.ID = "Div_Cabos_Rede";
testes.Attributes.Add("class", "col-md-12 letra");
testes.InnerHtml = "Cabos de rede";
TextBox Cabos_de_rede = new TextBox();
Cabos_de_rede.ID = "Txt_Cabos_Rede";
Cabos_de_rede.Attributes.Add("class", "col-md-12 form-control");
testes.InnerHtml = "Cabos de rede";
PlaceHolder1.Controls.Add(testes);
PlaceHolder1.Controls.Add(Cabos_de_rede);
}
protected void SubmitButton_Click(object sender, EventArgs e)
{
TextBox testar = FindControlRecursive(PlaceHolder1, "Txt_Cabos_Rede") as TextBox;
ResultLabel.Text = testar.Text;
}
// Custom method to search a control recursively
// in case it is nested inside other control.
// You can create it as an extension method if you would like.
public static Control FindControlRecursive(Control root, string id)
{
if (root.ID == id)
return root;
return root.Controls.Cast<Control>()
.Select(c => FindControlRecursive(c, id))
.FirstOrDefault(c => c != null);
}
}
I know you have a lot of questions. Before commenting on this question, please create a new project, and make this very simple code to work.
FindControl()but instead just inspect the raw form data in theRequestobject? (Side note: You're also trying to output theTextBoxobject itself, not it's.Textproperty.)FindControl()isn't working, can you debug into the control hierarchy inBodyand see if your dynamically created controls are there at all? If this is a post-back they might not be. However, any form values should still be in that HTML POST request. Are the key/value pairs you're looking for inRequest.Form? It's a more manual way to get the values, but manual seems to be the approach here.