views:

316

answers:

4

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
}
A: 

You will need some mechanism to create a relation between the Button and the TextBox obviously. In winforms this would be easy, where each control has a Tag property, which can contain a reference to pretty much anything. The web controls don't have such a property (that I know of), but it is still easy to maintain such relations. One approach would be to have Dictionary in the page storing button/textbox relations:

private Dictionary<Button, TextBox> _buttonTextBoxRelations = new  Dictionary<Button, TextBox>();

When you create the button and textbox controls, you insert them in the dictionary:

TextBox txtComment = new TextBox();
// ...

Button btnCommentSave = new Button();
// ...
_buttonTextBoxRelations.Add(btnCommentSave, txtComment);

...and then you can look up the text box in the button's click event:

protected void btnSave_Click(object sender, CommandEventArgs e)
{
    TextBox commentTextBox = _buttonTextBoxRelations[(Button)sender];
    firstelement.InnerText = txtComment.text // this gives error on txtComment.text
}
Fredrik Mörk
A: 

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.

Jamie Ide
A: 

Add an 'ID' to the textbox

txtComment.ID = "txtComment"

Request the information from the submitted form (provided you have a form on the page)

comment = Request.Form("txtComment")
A: 

Try during postback to load txtComment (with the same ID) in overridden LoadViewState method after calling base.LoadViewState. In this case you do load it before postback data are handled and txtComment control comes loaded.

Tadas