简体   繁体   English

找不到动态创建的文本框

[英]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: 此函数用于在db中保存文本框的值:

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. 我也将EnableViewState =“ true”放在了文件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. 有关更多信息,请参见asp.net页面生命周期 -您应该在Page.Init事件中创建动态控件,以便稍后使用。

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: 如果您知道TextBox id,则可以从Form集合中检索值,如果您只需要提交的值,则可以避免不必要地重新创建控件:

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;

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM