textbox dynamically created not found
I use this method for inserting a textbox in a tablecell
protected void EditAttivitaClick(object sender, EventArgs e)
{
string attivitaID = ((ImageButton)sender).ID.Split('_')[2];
tableCell =(HtmlTableCell)FindControl("AttivitaDescrizione_" + attivitaID);
TextBox txt = new TextBox();
txt.Text = tableCell.InnerHtml;
txt.ID = "TxtAttivitaDescrizione_" + attivitaID;
tableCell.InnerHtml = "";
}
It works correctly. And this function for saving in db the textbox's value:
protected void SalvaAttivitaClick(object sender, EventArgs e)
{
string attivitaID = ((ImageButton)sender).ID.Split('_')[2];
TextBox txt = (TextBox)FindControl("TxtAttivitaDescrizione_" + attivitaID);
string a = txt.Text;
attivitaTableAdapter.UpdateID(txt.Text, 开发者_运维百科Int32.Parse(attivitaID));
tableCell.Controls.Clear();
tableCell.InnerHtml = a;
}
But it doesn't work. beacuse it doesn't find the textbox created previously.
I've put also EnableViewState="true" in the file aspx.
Why?
You need to create the textbox every time the page is reloaded, this includes the post back.
See the asp.net page lifecycle for more information - you should create your dynamic controls in the Page.Init event, so it will be available later on.
If you know the TextBox id you can retrieve the value from the Form collection, this will save you having to recreate the control unnecessarily if you only need the submitted value:
string attivitaID = ((ImageButton)sender).ID.Split('_')[2];
if(Request.Form["TxtAttivitaDescrizione_" + attivitaID] != null)
{
string a = Request.Form["TxtAttivitaDescrizione_" + attivitaID];
attivitaTableAdapter.UpdateID(a, Int32.Parse(attivitaID));
tableCell.Controls.Clear();
tableCell.InnerHtml = a;
}
精彩评论