C# – How to read a dynamically created textbox

asp.netc++controlsdynamic

I create some dynamic textbox's and a button in a placeholder and would like to save info in textbox's when button is clicked but not sure how to retrieve data from the textbox

LiteralControl spacediv3 = new LiteralControl("&nbsp&nbsp");
Label  lblComText = new Label();
lblComTitle.Text = "Comment";
TextBox txtComment = new TextBox();
txtComment.Width = 200;
txtComment.TextMode = TextBoxMode.MultiLine;
phBlog.Controls.Add(lblComText);
phBlog.Controls.Add(spacediv3);
phBlog.Controls.Add(txtComment);

Button btnCommentSave = new Button();
btnCommentSave.ID = "mySavebtnComments" ;
btnCommentSave.Text = "Save ";
phBlog.Controls.Add(btnCommentSave);
btnCommentSave.CommandArgument = row["ID"].ToString();
btnCommentSave.Command += new CommandEventHandler(btnSave_Click);

protected void btnSave_Click(object sender, CommandEventArgs e)
{
    firstelement.InnerText = txtComment.text // this gives error on txtComment.text
}

Best Solution

You need to get a reference to your control in btnSave_Click. Something like:

protected void btnSave_Click(object sender, CommandEventArgs e)
{
    var btn = (Button)sender;
    var container = btn.NamingContainer;
    var txtBox = (TextBox)container.FindControl("txtComment");
    firstelement.InnerText = txtBox.text // this gives error on txtComment.text
}

You also need to set the ID on txtComment and recreate any dynamically created controls at postback.